在做一个软件授权相关的需求时,需要在中间件中过滤授权信息,同时需要考虑一些不需要检查授权的特殊情况。
所以有了使用自定义特性的思路,经过查找,找到如下实现方式:
- 定义自定义特性ActionAttribute.cs
public class MyAttribute : Attribute { public string Message { get; set; } public MyAttribute (string message ) { Message = message ; } }
- 自定义中间件类: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); } }
- 在Startup.cs中激活自定义中间件
app.UseMiddleware<MyMiddleware>();
- 使用方法
在控制器的各个方法上加上【MyAttribute】