0

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.

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

7 Comments

I am really new to MVS i think your method is inside a controller? But i don't want to add the annotations on each method, because i want this on each method.
@Flo I have updated my answer. You can also apply this filter on your controller.
Okay i will use the middleware as auth. And i want to call it on every rest controller and every method. Can i not configure it global?
@Flo It depends, If you need to handle cross-cutting business and application concerns you can use Filter instead, But if you need something globally then you can use Middlware. learn.microsoft.com/en-us/aspnet/core/mvc/controllers/…
@Flo define your middleware before app.UseMvc();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.