从操作筛选器属性重定向引发异常“在发送HTTP标头后无法重定向”

时间:2017-05-15 08:51:14

标签: asp.net-mvc redirect asp.net-web-api-routing

动作过滤器属性:

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时会抛出异常。

2 个答案:

答案 0 :(得分:0)

你不能这样做,根据MSDN DocumentationResponse.Redirect("url")会在

时抛出HttpExeption
  

在发送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;
    }
}