在一个地方定义Authorize属性,以便与多个ActionResults一起使用?

时间:2013-04-13 03:41:29

标签: asp.net-mvc-3 filter authorize

我在控制器或操作上使用Authorize属性,例如:

[Authorize(Roles="admin,user", Users="user1,user2")]
public ActionResult LogOn(LogOnModel model, string returnUrl) {
    return view();
}

但是,我必须在每个控制器或操作上将其定义为[Authorize(Roles="admin,user",Users="user1")]

如何在一个地方/文件中定义?

RegisterGlobalFilters这样做吗?我不知道如何使用全局过滤器定义[Authorize(Roles="*",Users="*")]

1 个答案:

答案 0 :(得分:1)

试试这个

创建新文件并在操作中使用此属性标题

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
   private readonly RoleEnum[] _acceptedRoles;


public AuthorizeAttribute(params RoleEnum[] acceptedroles)
{
    _acceptedRoles = acceptedroles;
}

public AuthorizeAttribute(params bool[] allowAll)
{
    if (allowAll[0])
        _acceptedRoles = new RoleEnum[] { RoleEnum.Admin, RoleEnum.user};
}

public void OnAuthorization(AuthorizationContext filterContext)
{
    if (SessionHelper.UserInSession == null)//user not logged in
    {
        FormsAuthentication.SignOut();
        filterContext.Result =
             new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary {{ "controller", "Home" },
                                         { "action", "Index" },
                                         { "returnUrl",    filterContext.HttpContext.Request.RawUrl } });//send the user to login page with return url
        return;
    }
    if (!_acceptedRoles.Any(acceptedRole => SessionHelper.UserInSession.UserRoles.Any(currentRole => acceptedRole == currentRole.Role)))
        //allow if any of the user roles is among accepted roles. Else redirect to login page
        throw new UnauthorizedAccessException();

 }
}

这也适用于返回网址

Reference