在AuthorizeAttribute

时间:2019-02-28 07:59:15

标签: c# asp.net-mvc asp.net-mvc-4 authorize-attribute

因此,我有两个自定义的授权属性:1)用于在会话过期或未通过身份验证时重定向用户以登录。 2)目前正在进行中。

第二个自定义授权属性的想法是在用户导航到下一页之前将其重定向到同一页面,或者防止用户重定向到下一页请求。假设代码是

public class CustomAuth2Attribute : AuthorizeAttribute
{
    private const string _errorController = "Error";

    public override void OnAuthorization(AuthorizationContext filterContext)
    {                        
        var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        var action = filterContext.ActionDescriptor.ActionName;

        var area = "";
        if (filterContext.RouteData.DataTokens.ContainsKey("area"))
            area = filterContext.RouteData.DataTokens["area"].ToString();

        if (controller == _errorController)
        {
            return;
        }


        // checking the user identity whether the user is allowed to access this page
        // then redirect to the previous page before this request and add flash note: "not allowed to access the content"

    }     
}

这个想法是,如果用户无权访问某个页面,则我不将其标记为未授权,而是应该将其返回到以前带有注释消息的页面。

还尝试了以下代码:

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
    controller,
    action,
    area
}));

我收到太多重定向,这是因为我引用的是当前控制器,操作和区域,而不是前一个。我也尝试获取UrlReferrer值,但这始终是null

有什么办法可以做到这一点?任何帮助表示赞赏。预先谢谢你。

1 个答案:

答案 0 :(得分:1)

为此,您可以覆盖HandleUnauthorizedResult

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    base.HandleUnauthorizedRequest(filterContext);

    filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.ToString());
}