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 09:39

If the route cannot be resolved, then MVC framework will through 404 error.. Best approach is to use Exception Filters ... Create a custom exceptionfilter and make like this..

public class RouteNotFoundAttribute : FilterAttribute, IExceptionFilter {
    public void OnException(ExceptionContext filterContext) {
        filterContext.Result  = new RedirectResult("~/Content/RouteNotFound.html");
   }
}
查看更多
The star\"
3楼-- · 2019-01-05 09:41

An alternative to creating a catch-all route is to add an Application_EndRequest method to your MvcApplication per Marco's Better-Than-Unicorns MVC 404 Answer.

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-05 09:41

Inside RouterConfig.cs add the follwing piece of code:

  routes.MapRoute(
           name: "Error",
           url: "{id}",
           defaults: new
           {
               controller = "Error",
               action = "PageNotFound"

           });
查看更多
ら.Afraid
5楼-- · 2019-01-05 09:48

Add this lines under your project root web.config File.

 <system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Test/PageNotFound" />
  <remove statusCode="500" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Test/PageNotFound" />
</httpErrors>
<modules>
  <remove name="FormsAuthentication" />
</modules>

查看更多
不美不萌又怎样
6楼-- · 2019-01-05 09:49

This might be a problem when you use

throw new HttpException(404);

When you want to catch that, I don't know any other way then editing your web config.

查看更多
Melony?
7楼-- · 2019-01-05 10:01

Found the answer myself.

Richard Dingwall has an excellent post going through various strategies. I particularly like the FilterAttribute solution. I'm not a fan of throwing exceptions around willy nilly, so i'll see if i can improve on that :)

For the global.asax, just add this code as your last route to register:

routes.MapRoute(
    "404-PageNotFound",
    "{*url}",
    new { controller = "StaticContent", action = "PageNotFound" }
    );
查看更多
登录 后发表回答