ASP.NET MVC 如何在不重写 URL 的情况下处理来自 Application_Error 的 404 错误

ASP.NET MVC how to handle 404 error from Application_Error without rewriting the URL

我创建了一个非常简单的 ASP.NET MVC 5 应用程序,我想在其中处理来自 Application_Error 的 404 异常,如 this question and in this other answer[=69 所示=].但是当我尝试访问一个不存在的页面时(并希望显示我的 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 页面的源代码: 不存在页面的输出:


我在 Whosebug 和其他网站上搜索了几个小时,但在这里找不到任何帮助。

有些人使用非常相似的代码来处理 404 异常,但没有相同的结果。我真的坚持这一点,我希望有人能帮助我,或者至少告诉我一个比 this answer 更好的方法来处理 ASP.NET MVC 中的 404 异常5.

如果您的浏览器中有纯文本 html,这可能意味着您的 header.

中的 Content-Type 值有误

试试这个:

Response.ContentType = "text/html"; 

这当然不是最好的解决方案,但它确实有效。

飞行棋