2015-01-07 57 views
2

我創建了一個非常簡單的ASP.NET MVC應用5,我想處理從我Application_Error 404的異常,如在this questionin this other answer網址。但是,當我嘗試訪問不存在的頁面(並期望我的404頁面被顯示時)我的自定義錯誤頁面的源代碼以純文本顯示!ASP.NET MVC如何處理的Application_Error 404錯誤,不重寫

我不想被rewrited我的網址爲in this post

我的項目是非常簡單的。我剛添加到基本ASP.NET WebApplication with Razor

  • 一個ErrorsController.cs
  • 的圖Http404.cshtml
  • 和編輯Global.asax

,如下所示:

項目組織:

Project organisation


的Global.asax:

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    {} 

    protected void Application_Error(object sender, EventArgs e) 
    { 
     Exception exception = Server.GetLastError(); 
     HttpException httpException = exception as HttpException; 

     RouteData routeData = new RouteData(); 
     routeData.Values.Add("controller", "Errors"); 

     if (httpException == null) 
     { 
      routeData.Values.Add("action", "Index"); 
     } 
     else 
     { 
      switch (httpException.GetHttpCode()) 
      { 
       case 404: 
        routeData.Values.Add("action", "Http404"); 
        break; 
      } 
     } 

     Response.Clear(); 
     Server.ClearError(); 
     Response.TrySkipIisCustomErrors = true; 

     IController errorController = new ErrorsController(); 
     errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); 
    } 
} 

ErrorsController.cs:

public class ErrorsController : Controller 
{ 
    public ActionResult Http404(string url) 
    { 
     return View("Http404"); 
    } 
} 

Http404.cshtml

@{ 
    ViewBag.Title = "Page not found"; 
} 

<h2>Page not found</h2> 

但後來當我試圖達到誰是不存在的一切,我看到的是我的404頁面的源代碼的頁面: 輸出不存在的頁:

Output when i reach a non existing page


我在stackoverflow和其他網站搜索了幾個小時,但沒有找到任何幫助我的地方。

有些人使用非常相似的代碼來處理404異常,但沒有相同的結果。我真的停留在此,我希望有人能夠幫助我,或者至少說明我比this answer一個更好的方法來處理404個例外ASP.NET MVC 5

回答

4

如果以純文本的HTML瀏覽器,這可能意味着你的頭中有一個錯誤的Content-Type值。

試試這個:

Response.ContentType = "text/html"; 

它肯定不是最好的解決辦法,但它的工作原理。

Ludo

+0

非常感謝!奇蹟般有效 ! –