Blog

Filter posts by Category Or Tag of the Blog section!

Difference Between Middleware and Filter in Asp.net Core

Wednesday, 29 September 2021

Both middleware and filter in asp.net core are used for handling incoming requests. Middleware is used for the entire request pipeline but filters are used for a specific requests. One of the biggest differences is that middleware has access to the HttpContext while filter has access to MVC (or API) context.  Look are the following simple Middleware:

 

public class CustomMiddleware
	{
		private readonly RequestDelegate _next;

		private readonly ILogger<CustomMiddleware> _logger;

		public CustomMiddleware(RequestDelegate next, ILogger<CustomMiddleware> logger)
		{
			_next = next ?? throw new ArgumentNullException(nameof(next));
			_logger = logger ?? throw new ArgumentNullException(nameof(logger));
		}

		public async Task Invoke(HttpContext httpContext)
		{
			await _next(httpContext);
		}
	}

 

usage of this middleware in program.cs is like the following:

 

var builder = WebApplication.CreateBuilder(args);



builder.Services.AddRazorPages();



var app = builder.Build();



app.Services.GetService<ICustomService>();



if (!app.Environment.IsDevelopment())

{

    app.UseExceptionHandler("/Error");

    app.UseHsts();

}



app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseMiddleware<CustomMiddleware>(); 

app.MapRazorPages();

app.Run();

 

Now bout a custom filter:

 

public class CustomActionFilter : IActionFilter
	{
		private readonly ILogger<CustomActionFilter> _logger;

		public CustomActionFilter(ILogger<CustomActionFilter> logger)
		{
			_logger = logger ?? throw new ArgumentNullException(nameof(logger));
		}

		public void OnActionExecuted(ActionExecutedContext context)
		{
			_logger.LogInformation($"From OnActionExecuted method of {nameof(CustomActionFilter)}");
		}

		public void OnActionExecuting(ActionExecutingContext context)
		{
			_logger.LogInformation($"From OnActionExecuting method of {nameof(CustomActionFilter)}");
		}
	}

 

And the usage of it in a controller:

 

[ApiController]
	[Route("[controller]")]
	[TypeFilter(typeof(CustomActionFilter))]
	public class WeatherForecastController : ControllerBase
	{

	}

 

The execution of middleware occurs before the Filters in the whole system, so it seems using middleware takes more attention.

Category: Software

Tags: Asp.Net

comments powered by Disqus