简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM