使用AuthorizeAttribute中的Flash消息重定向到同一页面

问题描述 投票:0回答:1

所以我有两个自定义授权属性: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

我能用这种方式做到吗?任何帮助表示赞赏。先感谢您。

c# asp.net-mvc asp.net-mvc-4 authorize-attribute
1个回答
1
投票

您可以为此覆盖HandleUnauthorizedResult

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

    filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.ToString());
}
© www.soinside.com 2019 - 2024. All rights reserved.