ASP.NET核心-MVC上的中间件 [英] ASP.NET core - middleware on MVC

查看:393
本文介绍了ASP.NET核心-MVC上的中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在macOS上创建一个asp.net核心Web api.

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

但是我的中间件没有在mvc-call上调用.

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

我的配置:

   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);
    }

我的中间件:

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);
    }
}

当我执行HTTP请求时,这与控制器请求不匹配.调用中间件类.

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

如何设置仅在mvc-request上调用中间件类.

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

推荐答案

您可以将中间件用作MVC过滤器:

You can use middleware as MVC filters:

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

在这种情况下,每次调用操作方法Index时,都会运行AuthMiddleware.

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

PS :您需要安装此软件包(

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

更多信息(请参阅作为MVC过滤器的中间件部分)

more info (see Middleware as MVC filters section)

这篇关于ASP.NET核心-MVC上的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆