ASP.NET Core 如何在中间件中获取自定义的特性

本文介绍了一种通过自定义特性实现API授权验证的方法。通过定义MyAttribute特性,并结合自定义中间件MyMiddleware,在.NET应用程序中对请求进行授权检查。文章详细展示了如何在控制器方法上应用该特性,并配置中间件来读取这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做一个软件授权相关的需求时,需要在中间件中过滤授权信息,同时需要考虑一些不需要检查授权的特殊情况。

所以有了使用自定义特性的思路,经过查找,找到如下实现方式:

  1. 定义自定义特性ActionAttribute.cs
        public class MyAttribute : Attribute
        {
            public string Message { get; set; }
    
            public MyAttribute (string message )
            {
                Message = message ;
            }
        }

     

  2. 自定义中间件类:MyMiddleware.cs
        public class MyMiddleware
        {
            private readonly RequestDelegate _next; 
    
            public MyMiddleware(RequestDelegate next, ActionLogService actionLogService)
            {
                _next = next; 
            }
    
            public async Task InvokeAsync(HttpContext context)
            {           
                var endpoint = context.GetEndpoint();
                
                if (endpoint != null)
                {
                    var myAttribute = endpoint.Metadata.GetMetadata<MyAttribute>();
                    if (myAttribute != null)
                    {
                        var message = myAttribute.Message;
                        // TODO ……
                        await _service.Add(log);
                    }
                    
                }
                
                await _next(context);
            }
        }

     

  3. 在Startup.cs中激活自定义中间件
    app.UseMiddleware<MyMiddleware>();

     

  4. 使用方法

        在控制器的各个方法上加上【MyAttribute】

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值