自定义授权属性附加Param?

Duc*_*tal 1 asp.net asp.net-mvc

我正在寻找一种方法来自定义我的授权属性,以便我可以使用我自己的MembershipProvider正确实现它.

我需要的是拥有IsInRoles(字符串角色,int perm),换句话说,我想让它替换为新的IsinRoles,或者可能创建另一种方法来存档此结果.

可能吗?或者我需要写一个不同的授权属性?

非常感谢您的关注......

PS:我在ASP.net MVC上工作,所以我需要启动[授权]过滤器.

Kel*_*sey 6

我认为您只需将公共属性添加到自定义AuthorizeAttribute即可.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// Add the allowed roles to this property.
    /// </summary>
    public YourCustomRoles RequiredRole;

    public int YourCustomValue;

    /// <summary>
    /// Checks to see if the user is authenticated and has the
    /// correct role to access a particular view.
    /// </summary>        
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null) throw new ArgumentNullException("httpContext");

        // Make sure the user is authenticated.
        if (httpContext.User.Identity.IsAuthenticated == false) return false;

        // Can use your properties if needed and do your checks
        bool authorized = DoSomeCustomChecksHere();

        return authorized;
    }
}
Run Code Online (Sandbox Code Playgroud)

用途我认为会(虽然没试过):

[CustomAuthorizeAttribute (RequiredRole=MyCustomRole.Role1 | MyCustomRole.Role2, YourCustomValue=1234)]
Run Code Online (Sandbox Code Playgroud)