如何在IEnumerable<CustomAttributeData>中检测Microsoft.AspNetCore.Authorization属性?
优化方案
直接通过typeof替代硬编码字符串
不需要手动写死属性的全名,利用typeof(AllowAnonymousAttribute)动态获取类型信息,既能避免硬编码,又能保证名称的准确性:
using Microsoft.AspNetCore.Authorization; // ... if (CustomAttributes.Any(item => item.AttributeType.FullName == typeof(AllowAnonymousAttribute).FullName)) { // 方法标记了[AllowAnonymous] }
更严谨的类型匹配(推荐)
如果要进一步提升准确性,直接对比AttributeType的类型实例,而非仅对比全名(可避免极少数情况下的命名冲突):
using Microsoft.AspNetCore.Authorization; // ... if (CustomAttributes.Any(item => item.AttributeType == typeof(AllowAnonymousAttribute))) { // 方法标记了[AllowAnonymous] }
封装扩展方法提升复用性(可选)
如果需要频繁检测这类授权属性,可以封装扩展方法简化代码:
using Microsoft.AspNetCore.Authorization; using System.Collections.Generic; using System.Reflection; public static class CustomAttributeDataExtensions { public static bool HasAllowAnonymous(this IEnumerable<CustomAttributeData> attributes) { return attributes.Any(attr => attr.AttributeType == typeof(AllowAnonymousAttribute)); } public static bool HasAuthorizeWithRole(this IEnumerable<CustomAttributeData> attributes, string role) { return attributes.Any(attr => attr.AttributeType == typeof(AuthorizeAttribute) && attr.NamedArguments.Any(arg => arg.MemberName == nameof(AuthorizeAttribute.Roles) && arg.TypedValue.Value?.ToString()?.Contains(role) == true)); } }
使用时会非常简洁:
if (CustomAttributes.HasAllowAnonymous()) { // 处理逻辑 } if (CustomAttributes.HasAuthorizeWithRole("admin")) { // 处理admin角色授权的情况 }
以上方案均利用.NET类型系统替代硬编码字符串,既保证了准确性,也提升了代码的可维护性。
内容的提问来源于stack exchange,提问作者wiki
相关产品推荐
相关产品推荐

