Search code examples
asp.net-web-apiasp.net-coremiddleware

ASP.NET core - middleware on MVC


I try to create an asp.net core web api on macOS.

But my middleware isn't called on mvc-call.

My Config:

   public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BackendDbContext context)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        //app.UseStaticFiles();

        app.UseMvc();
        app.UseMiddleware<AuthMiddleware>();

        BackendDbInitializer.Init(context);
    }

And my Middleware:

public class AuthMiddleware 
{
    private readonly RequestDelegate _next;

    public AuthMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine("Invoke......................");

        await _next.Invoke(context);
    }
}

When i do a HTTP-request, that doesn't match a controller request. The middleware class is called.

How can i set up that the middleware class is only called on a mvc-request.


Solution

  • You can use middleware as MVC filters:

    public class HomeController : Controller
    {
        [MiddlewareFilter(typeof(AuthMiddleware))]
        public IActionResult Index()  
        {
            return View();
        }
    }
    

    In this case, AuthMiddleware will run each time the action method Index is called.

    PS: You need to install this package (Microsoft.AspNetCore.Mvc.Core)

    more info (see Middleware as MVC filters section)