2013-12-20 64 views
0

我有以下對一個ASP.NET MVC應用5處理錯誤:無法處理ASP.NET MVC上的404錯誤。爲什麼?

protected void Application_Error() { 

    var exception = Server.GetLastError(); 
    var httpException = exception as HttpException; 
    Response.Clear(); 
    Server.ClearError(); 
    var routeData = new RouteData(); 
    routeData.Values["controller"] = "Errors"; 
    routeData.Values["action"] = "Internal"; 
    routeData.Values["exception"] = exception; 
    Response.StatusCode = 500; 
    if (httpException != null) { 
    Response.StatusCode = httpException.GetHttpCode(); 
    switch (Response.StatusCode) { 
     case 403: 
     routeData.Values["action"] = "Forbidden"; 
     break; 
     case 404: 
     routeData.Values["action"] = "NotFound"; 
     break; 
    } 
    } 
    // Avoid IIS7 getting in the middle 
    Response.TrySkipIisCustomErrors = true; 
    IController errorsController = new ErrorController(); 
    HttpContextWrapper wrapper = new HttpContextWrapper(Context); 
    var rc = new RequestContext(wrapper, routeData); 
    errorsController.Execute(rc); 
} 

這工作得很好,但是當我輸入,在地址欄中,一所沒有的URL我沒有得到404錯誤。

我什麼都試過了我能想到的,但沒有運氣...

任何想法,爲什麼?

謝謝你,

米格爾

回答

0
protected void Application_Error() 
      { 
       HttpContext httpContext = HttpContext.Current; 
       if (httpContext != null) 
       { 
        RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext; 
        /* when the is ajaxRequest the system can automatically handle a mistake with a JSON response. then overwrites the default response */ 
        if (requestContext.HttpContext.Request.IsAjaxRequest()) 
        { 
         httpContext.Response.Clear(); 
         string controllerName = requestContext.RouteData.GetRequiredString("controller"); 
         IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory(); 
         IController controller = factory.CreateController(requestContext, controllerName); 
         ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller); 

         JsonResult jsonResult = new JsonResult(); 
         jsonResult.Data = new { success = false, serverError = "500" }; 
         jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
         jsonResult.ExecuteResult(controllerContext); 
         httpContext.Response.End(); 
        } 
        else 
        { 
         var httpException = requestContext.HttpContext.Server.GetLastError() as HttpException; 
         int errorCode = httpException.GetHttpCode(); 
         switch(errorCode) 
         { 
          case 404: 
           httpContext.Response.Redirect("~/Error404"); 
           break; 
          default: 
           break; 
         } 
        } 
       }