我需要在每次浏览之前检查是否设置了某个会话。如果设置了会话,那么将允许用户访问他/她期望的页面。否则将他重定向到会话设置控制器&行动。为了摇晃我做了下面的任务。但我可以找到从过滤器重定向的方法。从自定义过滤器返回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.
}
}
}
答案 0 :(得分:0)
您还需要覆盖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" }));
}
}