【问题标题】:Middleware check the annotation from controller method中间件检查控制器方法的注释
【发布时间】:2016-12-15 10:48:02
【问题描述】:

您好,我想检查中间件类中控制器方法的注释。

我的配置:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BackendDbContext context)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseStaticFiles();
    app.UseMiddleware<AuthMiddleware>();
    app.UseMvc();

    BackendDbInitializer.Init(context);
}

我的控制器:

Route("api/[controller]")]
public class UserController : Controller
{
    private readonly BackendDbContext _context;

    public UserController(BackendDbContext context)
    {
        _context = context;
    }

    // GET api/values
    [HttpGet]
    [NoAuth]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

我的中间件:

public class AuthMiddleware 
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {

        //Here i want to check if the called method in UserController have a annotation...
        await _next.Invoke(context);
    }
}

在 AuthMiddleware 中我想检查被调用的方法是否有特定的注释。

【问题讨论】:

  • 中间件不知道 mvc 上下文。您需要使用过滤器来获取被调用的方法信息。
  • 你能举个例子吗?
  • 您是在尝试编写身份验证或授权中间件吗? ASP.NET 身份验证中间件读取请求凭据并设置 HttpContext.User。 Authorization 属性检查用户并授予或拒绝访问。
  • 我希望验证

标签: asp.net-core asp.net-core-mvc middleware


【解决方案1】:

我不知道这个问题是否过时,我今天遇到了同样的问题,我正在使用Casbin.Net包为我的asp dotnet核心项目实现RBAC,我需要实现一个可以识别的auth中间件带有[Authorize]注解的控制器,所以只有这些控制器需要检查权限,其他控制器不需要,下面是我的代码

rbac with asp dotnet core using casbin

你可以忽略依赖注入和casbin部分,在AuthzMiddleware.cs中,我使用context.User.Claims.Count() &gt; 0来检查当前请求是否通过了Authentication中间件。

【讨论】:

    猜你喜欢
    • 2012-02-27
    • 2017-10-29
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多