重定向到同一页面,并在oferizeattribute中使用Flash消息



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

我能做到这一点吗?任何帮助都将受到赞赏。预先感谢您。

您可以为此覆盖HandleUnauthorizedResult

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    base.HandleUnauthorizedRequest(filterContext);
    filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.ToString());
}

最新更新