【发布时间】:2015-03-05 08:30:15
【问题描述】:
我创建了一个非常简单的 ASP.NET MVC 5 应用程序,我想在其中处理来自 Application_Error 的 404 异常,如 this question 和 in this other answer 所示强>。但是当我尝试访问一个不存在的页面(并希望显示我的 404 页面)我的自定义错误页面的源代码以纯文本显示!。
我不希望我的 URL 被重写为 in this post
我的项目非常简单。我刚刚添加了一个基本的ASP.NET WebApplication with Razor:
-
ErrorsController.cs - 一个视图
Http404.cshtml - 和编辑
Global.asax
如下图:
项目组织:
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 页面的源代码: 不存在页面的输出:
我在 stackoverflow 和其他网站上搜索了几个小时,但在这里找不到任何帮助我的东西。
有些人使用非常相似的代码来处理 404 异常但没有相同的结果。我真的坚持这一点,我希望有人可以帮助我,或者至少向我展示比 this answer 更好的方法来处理 ASP.NET MVC 5 中的 404 异常。
【问题讨论】:
标签: c# asp.net asp.net-mvc razor error-handling