c# - 从 OnActionExecuting 访问方法的属性

标签 c# .net-core asp.net-mvc-filters

我想知道如何在 OnActionExecuting 覆盖方法中检查 Controller 方法是否具有特定属性,例如 AllowAnonymous

我试过这个:

var methodAttr = Attribute.GetCustomAttribute(context.ActionDescriptor.GetType(), typeof(AuthorizeAttribute));

但我总是得到一个 Null 值。

也试过这个:

MethodBase method = MethodBase.GetCurrentMethod();
AuthorizeAttribute methodAttr = (AuthorizeAttribute)method.GetCustomAttributes(typeof(AuthorizeAttribute), true)[0];

但是当没有 AuthorizeAttribute 时,我会得到一个超出范围的异常。

我该如何做这个检查?

最佳答案

根据您的标签,我假设这是针对 .net 核心的。 这是检查自定义属性的示例

var descriptor = (ControllerActionDescriptor) context.ActionDescriptor;
if (descriptor.MethodInfo.GetCustomAttribute<AuthorizeAttribute>() != null) { 
    //Do something
}

关于c# - 从 OnActionExecuting 访问方法的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50332280/

相关文章:

c# - 在异步操作运行时继续工作流程

.net - 不支持的表达式 : Non-overridable members (here: ) may not be used in setup/verification expressions

asp.net-core - 从 .Net Core 3 引用 .NET Framework DLL

ASP.NET。如何修改返回的 JSON (actionfilter)

asp.net-mvc - filters.Add 与 FilterProviders.Providers.Add

c# - 中继器搜索查询字符串

c# - 缺少 System.Windows.Freezable

c# - 如何使用 C# 读取此 json 字符串?

c# - 如何在没有不安全关键字的情况下获取结构的 Span<byte> View

c# - IFilterProvider 和关注点分离