MVC自定义错误页面显示原始HTML

时间:2016-05-26 21:29:47

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

所以我试图实现自定义404页面。我使用了来自this question的建议来使用它,404现在成功加载了想要的视图,但不知何故,整个页面被包装在预标签中,因此无法渲染。当我手动请求站点时,它渲染得很好,因此重新处理时可能会出现问题。输出如下:

输出:

<html>
     <head>
         <html><head><link rel="alternate stylesheet" type="text/css" href="resource://gre-resources/plaintext.css" title="Lange Zeilen umbrechen"
     </head>
     <body>
         <pre><!DOCTYPE html><html>... (my page html)</html></pre>
     </body>
</html>

Global.asax中

Exception ex = Server.GetLastError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");

Response.Clear();
...
} else if(ex is HttpException) {
    if (((HttpException)ex).GetHttpCode() == 404)
    {
        routeData.Values.Add("action", "HttpError404");
    }

    // Pass exception details to the target error View.
    routeData.Values.Add("error", ex);

    // Clear the error on server.
    Server.ClearError();

    // Avoid IIS7 getting in the middle
    Response.TrySkipIisCustomErrors = true;

    // Call target Controller and pass the routeData.
    IController errorController = new ErrorController();
    errorController.Execute(new RequestContext(
         new HttpContextWrapper(Context), routeData));
    }

ErrorController:

[HandleError]
public ActionResult HttpError404(string error)
{
    ViewBag.Title = "Page not found! 404";
    ViewBag.Description = error;
    Response.StatusCode = 404;
    Response.TrySkipIisCustomErrors = true;

    return View("Index");
}

更新 感谢M.Babcock,它只需添加Response.ContentType =“text / html”;到我的Controller-Method。

0 个答案:

没有答案
相关问题