我正在ASP.NET MVC 4 Web应用程序中创建自定义错误页面。我已经使用属性实现了OnException错误处理和控制器装饰,但我希望为不属于任何控制器路径的URL提供自定义错误页面,因此我采用了Global.asax的Application_Error。
在这个问题here中跟随@ Darin(感谢btw!)回复,我已经相应地设置了一切,但是当控制器在客户端呈现视图时我遇到了问题。 当它返回一个视图时,它会返回<pre>
标记内呈现的所有HTML。当我看到这个时,我正在使用Chrome的开发工具。这种情况发生在 Chrome,Safari和Mozilla中(可能更多,我没有费心去检查)。奇怪的是,虽然IE中的视图很好。我用Google搜索并查看了其他问题并且没有找到太多相关信息。有人会碰巧知道这种情况是如何发生的,为什么会这样?作为最后的努力,我考虑将视图作为一个字符串并使用return Content(...)
代替,但它看起来有点值得它。
tl; dr - 如果我可以对我的视图HTML在<pre>
标记内呈现的原因有所了解,那就太棒了!我确定它是特定于浏览器渲染的,但我不会解决这个问题只适用于IE。
控制器:
public class ErrorsController : Controller
{
public ActionResult PageNotFound()
{
Response.StatusCode = 404;
var vm = new ErrorViewModel()
{
ErrorMessage = "The page you requested could not be found.",
StatusCode = Response.StatusCode
};
Response.TrySkipIisCustomErrors = true;
return View("PageNotFound", vm);
}
查看:
@{
Layout = "~/Views/Shared/_GenericLayout.cshtml";
}
<h1 class="error">Oh No!</h1>
@if(Model.ErrorMessage != null && Model.StatusCode != null)
{
<h2><em>@Model.StatusCode</em> - @Model.ErrorMessage</h2>
}
else
{
<h2>The page you requested could not be found.</h2>
}
的Global.asax:
protected void Application_Error(object sender, EventArgs e)
{
if (Context.IsCustomErrorEnabled)
{
ShowCustomErrorPage(Server.GetLastError());
}
}
private void ShowCustomErrorPage(Exception exception)
{
HttpException httpException = exception as HttpException;
Response.Clear();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Errors");
routeData.Values.Add("fromAppErrorEvent", true);
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch(Response.StatusCode)
{
case 404:
routeData.Values.Add("action", "PageNotFound");
break;
case 403:
routeData.Values.Add("action", "PageForbidden");
break;
}
}
Server.ClearError();
IController controller = new ErrorsController();
RequestContext rc = new RequestContext(new HttpContextWrapper(Context), routeData);
controller.Execute(rc);
}
答案 0 :(得分:3)
简单修复。 Chrome无法识别它收到的内容,因此在返回视图之前将响应的内容类型明确定义为“text / html”修复了问题。
public ActionResult PageNotFound()
{
Response.StatusCode = 404;
var vm = new ErrorViewModel()
{
ErrorMessage = "The page you requested could not be found.",
StatusCode = Response.StatusCode
};
Response.ContentType = "text/html";
Response.TrySkipIisCustomErrors = true;
return View("PageNotFound", vm);
}