C# 重定向到属性中包含flash消息的同一页面

C# 重定向到属性中包含flash消息的同一页面,c#,asp.net-mvc,asp.net-mvc-4,authorize-attribute,C#,Asp.net Mvc,Asp.net Mvc 4,Authorize Attribute,因此,我有两个自定义授权属性:1是在会话过期或未经身份验证时重定向用户登录;2目前正在进行中 第二个自定义authorize属性的想法是在用户导航到下一页之前将其重定向到同一页,或者防止重定向到下一页请求。假设代码是 public class CustomAuth2Attribute : AuthorizeAttribute { private const string _errorController = "Error"; public override void OnAut

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

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

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
}));
我得到的重定向太多,这是因为我引用的是当前控制器、操作和区域,而不是前一个。我还尝试获取URLreferer值,但该值始终为空

我有什么办法可以做到这一点?感谢您的帮助。提前感谢。

您可以为此覆盖HandleUnauthorizedResult:

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

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

HandleUnauthorizedRequest即使在重写时也不会被触发您是否调用AuthorizeCore?在你的问题中没有完全公布你的授权,所以这很难说。作为基线,AuthorizationCore应该处理您的授权逻辑,并且您至少应该调用base.OnAuthorizationfilterContext