How to make a catch all route to handle '404 p

2019-01-05 09:39发布

Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?

NOTE: I don't want to set this up in my IIS settings.

8条回答
我命由我不由天
2楼-- · 2019-01-05 10:04

This question came first, but the easier answer came in a later question:

Routing for custom ASP.NET MVC 404 Error page

I got my error handling to work by creating an ErrorController that returns the views in this article. I also had to add the "Catch All" to the route in global.asax.

I cannot see how it will get to any of these error pages if it is not in the Web.config..? My Web.config had to specify:

customErrors mode="On" defaultRedirect="~/Error/Unknown"

and then I also added:

error statusCode="404" redirect="~/Error/NotFound"

Hope this helps.

I love this way now because it is so simple:

 <customErrors mode="On" defaultRedirect="~/Error/" redirectMode="ResponseRedirect">
    <error statusCode="404" redirect="~/Error/PageNotFound/" />
 </customErrors>
查看更多
疯言疯语
3楼-- · 2019-01-05 10:06

Also you can handle NOT FOUND error in Global.asax.cs as below

protected void Application_Error(object sender, EventArgs e)
{
    Exception lastErrorInfo = Server.GetLastError();
    Exception errorInfo = null;

    bool isNotFound = false;
    if (lastErrorInfo != null)
    {
        errorInfo = lastErrorInfo.GetBaseException();
        var error = errorInfo as HttpException;
        if (error != null)
            isNotFound = error.GetHttpCode() == (int)HttpStatusCode.NotFound;
    }
    if (isNotFound)
    {
        Server.ClearError();
        Response.Redirect("~/Error/NotFound");// Do what you need to render in view
    }
}
查看更多
登录 后发表回答