ASP.NET MVC how to handle 404 error from Applicati

2019-05-22 13:45发布

I have created a really simple ASP.NET MVC 5 application where i want to handle the 404 exception from my Application_Error as shown in this question and in this other answer. But when i try to reach a page who don't exist (and expect my 404 page to be displayed) the source code of my custom error page is shown in plain text!.

I don't want my URL to be rewrited as in this post

My project is really simple. I just added to a basic ASP.NET WebApplication with Razor:

  • an ErrorsController.cs
  • a view Http404.cshtml
  • and edited Global.asax

as shown below:

Project organisation:

Project organisation


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>

But then when i try to reach a page who don't exist everything i see is the source code of my 404 page: output for a non existing page:

Output when i reach a non existing page


I searched for hours in stackoverflow and other site but found nothing to help me here.

Some people use very similar code to handle the 404 exception but don't have the same result. I'm really stuck on this, i hope someone could help me, or at least show me a better approach than this answer to handle 404 exceptions in ASP.NET MVC 5.

1条回答
冷血范
2楼-- · 2019-05-22 14:18

If you have plain text html in your browser, it may mean you have a wrong Content-Type value in your header.

Try this :

Response.ContentType = "text/html"; 

it is certainly not the best solution, but it works.

Ludo

查看更多
登录 后发表回答