How to pass dynamic variable to authorize attribute class in asp.net mvc?

How to pass dynamic variable to authorize attribute class in asp.net mvc?

For example, I have this piece of code, how do I pass a variable of type variable userRoles to the attribute class 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();

}

My code is causing this error

Error 1 The attribute argument must be a constant expression, typeof expression or expression to create an array of attribute parameter type C: \ Users \ Nashat \ Downloads \ New folder (3) \ MvcPWy \ Controllers \ HomeController.cs 39 28 MvcPWy

So please, can someone help me resolve this error.

+4
source share
3 answers

: . .

+1
    [Authorize(Roles = Roles.UserRoles)]
    public ActionResult Index()
    {
        return View();
    }

, - :

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

Source: https://habr.com/ru/post/1620171/


All Articles