Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
Mohamad Haidar Avatar asked Dec 15 '15 17:12

Mohamad Haidar


People also ask

How does Authorize attribute work in ASP.NET MVC?

The Authorize Attribute In ASP.NET MVC, any incoming request is bound to a controller/method pair and served. This means that once the request matches a supported route and is resolved to controller and method, it gets executed no matter what.

What is AllowAnonymous attribute in MVC?

The AllowAnonymous attribute in MVC is used to skip the authorization which is enforced by Authorization Filter in MVC. [AllowAnonymous] public ActionResult NonSecured() { return View();

Where can the Authorize attribute can be applied?

The Authorize attribute enables you to restrict access to resources based on roles. It is a declarative attribute that can be applied to a controller or an action method.


1 Answers

    [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";
}
like image 72
Alison Henrique Jonck Avatar answered Sep 29 '22 08:09

Alison Henrique Jonck