自定义授权属性附加Param?

时间:2009-09-20 03:26:49

标签: asp.net asp.net-mvc

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

我需要的是拥有IsInRoles(字符串角色,int perm),换句话说,我希望用新的IsinRoles替换它,或者创建另一种方法来存档这个结果。

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

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

PS:我正在开发ASP.net MVC,所以我需要启动并运行[Authorize]过滤器。

1 个答案:

答案 0 :(得分: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;
    }
}

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

[CustomAuthorizeAttribute (RequiredRole=MyCustomRole.Role1 | MyCustomRole.Role2, YourCustomValue=1234)]