动作过滤器属性:
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Controller controller = filterContext.Controller as Controller;
if (controller != null)
{
if (tokenContainer.ApiToken == null)
{
filterContext.Canceled = true;
controller.HttpContext.Response.Redirect("./Login");
}
}
}
尝试重定向到Login Action时会抛出异常。
答案 0 :(得分:0)
你不能这样做,根据MSDN Documentation,Response.Redirect("url")
会在
在发送HTTP标头后尝试重定向
所以你可以在调用之前检查Response.IsRequestBeingRedirected
属性(bool)。
喜欢:
// Causes headers to be sent to the client (Http "Location" response header)
Response.Redirect("http://www.stackoverflow.com");
if (!Response.IsRequestBeingRedirected)
// Will not be called
Response.Redirect("URL");
答案 1 :(得分:0)
您无需重定向。设置ActionExecutingContext
的结果以将您路由到您想去的地方。
你想要这样的东西:
public class CustomSecurityAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (tokenContainer.ApiToken != null) return;
//this will re-route you action
filterContext.Result = new ViewResult
{
ViewName = "Login", //whatever view you are routing to
ViewData = new ViewDataDictionary<HandleErrorInfo>(model), //you can leave it blank if your view doesn't need data
TempData = filterContext.Controller.TempData
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 403;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}