抛出exeption时如何解决ERR_TOO_MANY_REDIRECTS?

时间:2017-12-19 11:14:08

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

我已实施错误处理:

    protected void Application_Error(object sender, EventArgs e)
    {
        var ctx = HttpContext.Current;

        var exception = ctx.Server.GetLastError();

        bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase);
        Context.ClearError();
        _log.Error("errorr occured, error:  " + exception.Message);

        if (isAjaxCall)
        {
            //Context.Response.ContentType = "application/json";
            Context.Response.StatusCode = 500;
            Context.Response.Write(
                new JavaScriptSerializer().Serialize(
                    new { error = exception.Message }
                )
            );
        }

        else
        {
            HttpContext.Current.Response.RedirectToRoute("Error");
        }

    }

并在控制器中测试它:

    // GET: Book
    public ActionResult Index()
    {
        try
        {
            throw new Exception("test");
        }
        catch (Exception e)
        {

            throw e;
        }

        return View("BooksMain");
    }

这应该将我重定向到我的错误控制器

public class ErrorController : Controller
{
    // GET: Error
    public ActionResult Index()
    {
        return View();
    }

    [AllowAnonymous]
    public ActionResult ErrorPage()
    {
        return View();
    }
}

路线:

        routes.MapRoute(
             name: "Error",
             url: "Error",
             defaults: new { controller = "Error", action = "ErrorPage" }
        );

我得到的只是

  

ERR_TOO_MANY_REDIRECTS

在浏览器中

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您为"错误"定义的网址是不正确的。试试这个:

routes.MapRoute(
    "Error",
    "Error/ErrorPage",
    new { controller = "Error", action = "ErrorPage" }
);