-1

so i have the next problem. I have a controller and some user roles. I'm using string when i have [Authorize(Roles="Admin")] but i want to use an enum like that because if i change the name of role i will modify in one single place. I already tried Roles=UserRoles.Admin.ToString(), where UserRoles is my enum but i'm getting an error. I already read aricles from here but seems that no one helps me to solve my problem.

Could you help me with any suggestion?

tereško
  • 58,060
  • 25
  • 98
  • 150
lolex
  • 65
  • 11
  • Create a custom `AuthorizeAttribute` see something like this: http://stackoverflow.com/questions/13264496/asp-net-mvc-4-custom-authorize-attribute-with-permission-codes-without-roles – Ric Oct 05 '15 at 08:09

2 Answers2

3

Create a custom AuthorizeAttribute like this:

using System.Collections.Generic;
using System.Web.Mvc;

namespace MyApp.Whatever
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public CustomAuthorizeAttribute(params UserRoles[] userRoles)
        {
            Roles = string.Join(",", userRoles);
        }
    }
}

Then you can use it as you would usually use the AuthorizeAttribute, like this:

using System.Web.Mvc;

namespace MyApp.Whatever
{
    [CustomAuthorize(UserRoles.Admin, UserRoles.Whatever)]
    public class MyController : Controller
    {
        ...
    }
}
Jamie Dunstan
  • 3,725
  • 2
  • 24
  • 38
1

This can be done, but you need to do a little work.

  • Create you own custom attribute implementing IAuthorizationFilter (as AuthorizeAttribute does)
  • Accept your enumeration in its constructor (or via a property)
  • Forward operations to a contained instance of AuthorizeAttribute

(The whole filter mechanism is extensible to allow this kind of thing.)

However, what I have done in the past, to deal with this is to define a series of constant strings which are passed to the attribute's instances. Thus keeping the names central.

Richard
  • 106,783
  • 21
  • 203
  • 265