【问题标题】:ASP.NET MVC how to handle 404 error from Application_Error without rewriting the URLASP.NET MVC 如何在不重写 URL 的情况下处理来自 Application_Error 的 404 错误
【发布时间】:2015-03-05 08:30:15
【问题描述】:

我创建了一个非常简单的 ASP.NET MVC 5 应用程序,我想在其中处理来自 Application_Error 的 404 异常,如 this questionin 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


    【解决方案1】:

    如果您的浏览器中有纯文本 html,这可能意味着您的标头中有错误的 Content-Type 值。

    试试这个:

    Response.ContentType = "text/html"; 
    

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

    卢多

    【讨论】:

    • 非常感谢!像魅力一样工作!
    猜你喜欢
    • 2010-11-13
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    相关资源
    最近更新 更多