【问题标题】:How to pass a dynamic variable into the authorize attribute class in asp.net mvc?如何将动态变量传递给asp.net mvc中的授权属性类?
【发布时间】:2016-03-21 14:53:59
【问题描述】:

asp.net mvc中如何将动态变量传递给authorize属性类?

例如我有这段代码,如何将 userRoles 等变量传递给 Authorize 属性类?

private  string userRoles;
private string getuserRoles() 
{
     //Write your code to get userRoles
     userRoles = "admin";
     return "admin";
 }

[Authorize(Roles = object.getuserRoles())]
public ActionResult Admin()
{
       ViewBag.Message = "Your contact page.";

        return View();

}

我的代码出现这个错误

错误 1 ​​属性参数必须是常量表达式 typeof 属性参数的表达式或数组创建表达式 键入 C:\Users\Nashat\Downloads\New 文件夹 (3)\MvcPWy\Controllers\HomeController.cs 39 28 MvcPWy

所以请谁能帮我解决这个错误。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4 class-attributes


    【解决方案1】:
        [Authorize(Roles = Roles.UserRoles)]
        public ActionResult Index()
        {
            return View();
        }
    

    您必须为角色传递一个常量变量,如下所示:

    public static class Roles
    {
        public const string UserRoles = "UserRoles";
    }
    

    【讨论】:

      【解决方案2】:

      简单的答案是:你不能那样做。请查看此previous answer 了解更多详情。

      【讨论】:

        【解决方案3】:
        猜你喜欢
        • 1970-01-01
        • 2019-06-05
        • 2017-04-20
        • 1970-01-01
        • 2019-05-26
        • 2020-01-09
        • 2019-02-25
        • 2018-11-23
        相关资源
        最近更新 更多