且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC RoleProvider并授权属性

更新时间:2023-10-07 11:58:16

VoodooChild 回答#1。

有关#2 -

你可以做的是检查,如果用户登录在登录页面,并显示不同的消息或完全不同的页面(甚至做一个重定向到一个不同的动作)。

What you can do is check if the user is logged on the login page and display a different message or an entirely different page (or even do a redirect to a different action).

另外,您可以创建自己的授权属性。这将要求你在任何地方使用,而不是默认此属性 AuthorizeAttribute

Alternatively you can create your own authorization attribute. This will require that you use this attribute everywhere instead of the default AuthorizeAttribute

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(
                               new RouteValueDictionary 
                               {
                                   { "action", "ActionName" },
                                   { "controller", "ControllerName" }
                               });
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

更新:

只要想到另一种方法。当一个重定向从不同的页面做了登录页面,查询字符串 RETURNURL 也过去了。所以,你也可以检查,如果它包含的东西,用户通过验证,那么有可能在用户没有权限查看该页面。

Update:

Just thought of another method. When a redirect is done to login page from a different page, a querystring ReturnUrl is also passed. So you can also check if it contains something AND the user is authenticated, chances are the user didn't have permission to view that page.