[英]IIS Serves Custom Error page as plain text, no content-type header
我有簡單的vanilla MVC4網絡項目。 沒有添加,沒有刪除,只是在Visual Studio中創建了一個新項目。
在web.config
我添加了自定義錯誤頁面處理程序:
<customErrors mode="On" defaultRedirect="~/Content/Error.htm" redirectMode="ResponseRewrite" />
和~/Content/Error.htm
文件是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>OOPS! Error Occurred. Sorry about this.</title>
</head>
<body>
<h2>OOPS! Error Occurred</h2>
</body>
</html>
每當我在網站上收到404錯誤時,Error.htm在Firefox和Chrome中作為純文本提供:
Fiddler說錯誤頁面沒有content-type
標題,導致瀏覽器將頁面呈現為純文本:
有沒有辦法強制IIS服務器錯誤頁面具有content-type
標題?
ps實際問題出在一個復雜的MVC4項目中,它在Global.asax中有自己的錯誤處理。 但我發現有些錯誤不會通過ASP管道,只能由IIS處理。 像網址末尾的點 。 使用<httpErrors />的解決方案確實提供了正確的響應,但我們在Global.asax,Application_Error()中的自定義錯誤處理不會以這種方式調用。
UPD似乎無法贏得這場戰爭。 IE顯示正確呈現的html,Firefox和Chrome顯示為純文本。 當我切換到純文本時,Firefox和IE正確顯示空白區域,IE吞下白色空間並嘗試渲染html。 如果我嘗試將圖像作為錯誤頁面提供,則Firefox和Chrome會顯示圖像。 IE顯示了這個: 捂臉!
對於錯誤頁面使用.aspx而不是.htm(將htm重命名為aspx)。
<customErrors mode="On" defaultRedirect="~/Content/Error.aspx" redirectMode="ResponseRewrite" />
顯然, <customErrors>
是一個混亂的工作。 如果您決定使用它,Ben Foster對此主題有一個很好的寫作: http : //benfoster.io/blog/aspnet-mvc-custom-error-pages
如果你想使用.cshtml頁面,最好的辦法就是拋棄<customErrors>
並處理Global.asax.cs中的錯誤:
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
if (exception != null)
{
Response.Clear();
HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException == null)
{
routeData.Values.Add("action", "Unknown");
}
else
{
switch (httpException.GetHttpCode())
{
case 404: // Page not found.
routeData.Values.Add("action", "NotFound");
break;
default:
routeData.Values.Add("action", "Unknown");
break;
}
}
// Pass exception details to the target error View.
routeData.Values.Add("Error", exception);
// Clear the error on server.
Server.ClearError();
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
// Ensure content-type header is present
Response.Headers.Add("Content-Type", "text/html");
// Call target Controller and pass the routeData.
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}
當然,您還需要使用適當的方法和.cshtml視圖添加ErrorController。
public class ErrorController : Controller
{
public ActionResult Index()
{// your implementation
}
public ActionResult Unknown(Exception error)
{// your implementation
}
public ActionResult NotFound(Exception error)
{// your implementation
}
}
這顯然是一個已知的錯誤,微軟的建議符合spiatrax將htm / html重命名為aspx的想法。 在我的情況下,我也必須包括
<% Response.StatusCode = 400 %>
在.aspx頁面中。
有關更多信息,請訪問: http : //connect.microsoft.com/VisualStudio/feedback/details/507171/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.