【问题标题】:Returning false from ASP MVC Filter by default Redirecting to Account Controller默认情况下从 ASP MVC 过滤器返回 false 重定向到帐户控制器
【发布时间】:2015-09-27 09:49:26
【问题描述】:

我需要在每次浏览之前检查是否设置了某个会话。如果设置了会话,那么将允许用户访问他/她想要的页面。否则将他重定向到会话设置控制器和操作。对于摇晃,我做了以下任务。但我可以找到从过滤器重定向的方法。当从自定义过滤器返回 false 时,它​​会重定向到 Account Controller。我会非常感谢他会帮助我。
在我的 Global.asax.cs 中,我编写了以下代码:

 protected void Application_Start()
 {
     ......
     ......
     RegisterGlobalFilters(GlobalFilters.Filters);
 }

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 { 
     filters.Add(new CustomFilters()); 
 }

然后我在我的 Filter/CustomFilters.cs 目录中添加了如下代码。

[AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Class| AttributeTargets.Method)]
public class CustomFilters : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Session["HamdunSoft"] == "HamdunSoft")
        {
            return true;
        }
        else
        {
          return false; //I need to redirect to my custom Controller/Action. But from here
                         it is redirecting  Account Controller default.
        }
    }
}

【问题讨论】:

  • httpContext.Response.StatusCode = 302; httpContext.Response.RedirectLocation= "your custom Controller/Action"; httpContext.Response.End();
  • 谢谢,但是当返回 false 时,您能否告诉我代码控制的位置。表示帐户控制器的重定向代码在哪里:)? @KhanhTO
  • 当你return false时,它只是退出CustomFilters的代码,但流程还在继续。重定向代码是我向您展示的所有代码,它确实停止了当前的请求处理并向浏览器发送 http 302 重定向,浏览器发送另一个请求并重新启动流程

标签: c# asp.net asp.net-mvc asp.net-mvc-4 filter


【解决方案1】:

您还需要重写 HandleUnauthorizedRequest 函数,以便您可以重定向到所需的位置:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if(filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            if (httpContext.Session["HamdunSoft"] != "HamdunSoft")
            {
                filterContext.Result = new RedirectToRouteResult(new
                RouteValueDictionary(new{ controller = "YourCustomController", action = "YourCustomAction" }));
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new{ controller = "Error", action = "AccessDenied" }));
        }
    }

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多