ASP.NET Core 6+Swashbuckle中ActionDescriptor的GetCustomAttributes方法位置
在ASP.NET Core 6 Web API中获取自定义属性的替代方案
在ASP.NET Core 6的IOperationFilter实现里,原ASP.NET Web API 2中GetCustomAttributes<T>方法的替代方式有两种常用途径:
1. 通过ActionDescriptor的EndpointMetadata筛选
你可以从context.ApiDescription.ActionDescriptor的EndpointMetadata集合中筛选目标自定义属性,示例代码如下:
var customAttributes = context.ApiDescription.ActionDescriptor.EndpointMetadata .OfType<MyCustomAttribute>() .ToList();
这是官方推荐的获取方式,因为EndpointMetadata是ASP.NET Core中存储端点所有相关元数据(包括自定义属性)的统一集合,能更好适配端点路由模型。
2. 通过MethodInfo直接获取属性
如果自定义属性标记在控制器方法上,也可以通过context.MethodInfo结合反射获取:
var customAttributes = context.MethodInfo.GetCustomAttributes<MyCustomAttribute>(inherit: true);
内容的提问来源于stack exchange,提问作者HelloWorld
相关产品推荐
相关产品推荐

