在做一个软件授权相关的需求时,需要在中间件中过滤授权信息,同时需要考虑一些不需要检查授权的特殊情况。
所以有了使用自定义特性的思路,经过查找,找到如下实现方式:
- 定义自定义特性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】

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





