重定向的循环相当清晰。您的重定向请求必须是可识别的,以便您的代码可以检查并且不对该重定向请求执行重定向(因此不会执行循环并导致过多重定向错误)。
您的代码可以像这样简单:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
//obtain the controller instance
var controller = context.Controller as Controller;
//not sure where you define the GoToLogin here, I assume it's available as a bool
GoToLogin &= !Equals(controller.TempData["__redirected"], true);
if (GoToLogin)
{
//set a temp data value to help identify this kind of redirected request
//which will be later sent by the client.
//The temp data value will be deleted the next time read (the code above)
controller.TempData["__redirected"] = true;
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "controller", "account" },
{ "action", "login" }
});
}
}
注意:您的代码中的GoToLogin 不清楚,如果您的意思是您不知道它的条件是什么(以防止重定向循环) ,只要这样设置:
var goToLogin = !Equals(controller.TempData["__redirected"], true);
或者不改变它的值:
if (GoToLogin && !Equals(controller.TempData["__redirected"], true)){
//redirect the request ...
}
在这里使用TempData 的好处是可以在第一次阅读后自动删除。所以在接收到重定向请求的时候,TempData中包含的值为true,使得整个GoToLoginfalse(或者不满足重定向的条件),重定向将不会进行。之后,TempData 中包含的值将被清除(删除)并为下一次重定向做好准备。