mohaidar
mohaidar

Reputation: 4251

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

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

For Example I have this piece of code, how can I pass a variable like userRoles variable into the Authorize attribute class?

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 issues this error

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

So please could anyone help me to resolve this error.

Upvotes: 8

Views: 6684

Answers (3)

Alison Henrique Jonck
Alison Henrique Jonck

Reputation: 99

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

You have to pass a constant variable for Roles, something like this:

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

Upvotes: 2

Maess
Maess

Reputation: 4146

The simple answer is: You can't do that. Have a look at this previous answer for more detail.

Upvotes: 1

Related Questions