문제

I'm trying to create my own [Authorize] Attribute so I can use my own authorize logic to have hierarchal roles.

If someone does [Authorize(Roles = "Admin")] on a controller or action How do I get the string "Admin" in my AuthorizeCore function?

I'm using this code:

public class Authorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //authorize role logic
            if (true)
                return true;

        return false;
     }
    }

MVC4, .net 4.5, c#, VS 2012

도움이 되었습니까?

해결책

It is quit a common thing that you have faced with.

This recommendation in post should work in MVC4 as it is working in MVC 3: - ASP.NET MVC - Alternative to Role Provider?

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool isAdmin;
        if(Roles.Contains("Admin"))
           isAdmin = true;

        return isAdmin ;
    }

다른 팁

Roles is a public property. You should be able to do this:

public class Authorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {

        if(Roles.Contains("MyRole"))
           return true;

        return false;
    }
}

Or whatever it is that you need to do

If you need to get the list of allowed roles, you can simply get the Roles property. It will list the string that was specified in the attribute decoration.

public class Authorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var allowedRoles = Roles;
    }
}

You can see this on the AuthorizeAttribute definition

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top