【问题标题】:How to check Whether method have AllowAnonymous attribute or not in C# MVC如何在 C# MVC 中检查方法是否具有 AllowAnonymous 属性
【发布时间】:2020-05-14 19:05:53
【问题描述】:

我有控制器,其中某些方法具有授权属性,某些方法具有 AllowAnonymous 所以,我想在调用方法时检查是 Authorize 还是 AllowAnonymous

这是我的控制器,方法名为 login

[AllowAnonymouse]

Public ActionResult Login(){}

所以在不同的类中我想检查这个方法是 Authorize 还是 AllowAnonymous

【问题讨论】:

  • 使用反射,typeof(YourController).GetMethod("Login").GetCustomAttributes()

标签: c# asp.net-mvc


【解决方案1】:
string actionName = ViewContext.RouteData.Values["Action"]
MethodInfo method = type.GetMethod(actionName);
var attribute = method.GetCustomAttributes(typeof(DisplayNameAttribute), false);
if (attribute.Length > 0)
   actionName = ((DisplayNameAttribute)attribute[0]).DisplayName;
else 
   actionName = type.Name;

查看此链接:

Get attribute of current controller action in MVC View

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-05
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2015-11-04
    相关资源
    最近更新 更多