我正在ASP.NET MVC 4 Web应用程序中创建自定义错误页面。我已经用属性实现了OnException错误处理和 Controller 修饰,但是我想为不属于任何 Controller 路由的URL创建自定义错误页面,因此我求助于Global.asax的Application_Error。
在此问题here的@Darin(感谢btw!)响应之后,我进行了相应的设置,但是当 Controller 在客户端渲染 View 时出现问题。 返回 View 时,它返回在<pre>
标记内呈现的所有HTML。 看到此消息后,我正在使用Chrome的开发工具。这种情况发生在 Chrome,Safari和Mozilla(也许更多,我不愿意再检查这些)中。奇怪的是,尽管这些 View 在IE中呈现良好。我已经四处搜寻,环顾了其他问题,但没有发现太多。会有人碰巧知道这是怎么/为什么发生的,并为此解决方法吗?作为最后的努力,我考虑过将View作为字符串获取,而改用return Content(...)
,但这样做的值(value)似乎有点不足。
tl; dr-如果我可以输入一些有关为什么我的 View HTML在<pre>
标记内呈现的信息,那真是太棒了!我确定它是特定于浏览器呈现的,但是我不会确定这仅适用于IE。
Controller :
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);
}
View :
@{
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);
}
最佳答案
简单修复。 Chrome无法识别接收到的内容,因此在返回 View 之前将响应的内容类型显式定义为“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);
}
关于asp.net - ASP.NET MVC 4自定义错误 View 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290581/