You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:35:02