asp.net-mvc ASP.NET MVC - 捕获所有路由和默认路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4001081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC - Catch All Route And Default Route
提问by Sean Taylor
In trying to get my application to produce 404 errors correctly, I have implemented a catch all route at the end of my route table, as shown below:
为了让我的应用程序正确产生 404 错误,我在路由表的末尾实现了一个捕获所有路由,如下所示:
routes.MapRoute(
"NotFound", _
"{*url}", _
New With {.controller = "Error", .action = "PageNotFound"} _
)
However, to get this working, I had to remove the default route:
但是,要使其正常工作,我必须删除默认路由:
{controller}/action/{id}
But now that the default has been removed, most of my action links no longer work, and the only way I have found to get them working again is to add individual routes for each controller/action.
但是现在默认值已被删除,我的大多数操作链接不再有效,我发现让它们再次工作的唯一方法是为每个控制器/操作添加单独的路由。
Is there a simpler way of doing this, rather than adding a route for each controller/action?
有没有更简单的方法来做到这一点,而不是为每个控制器/动作添加一个路由?
Is it possible to create a default route that still allows the catch all route to work if the user tries to navigate to an unknown route?
如果用户尝试导航到未知路线,是否可以创建仍然允许捕获所有路线工作的默认路线?
回答by Robert Koritnik
Use route constraints
使用路由约束
In your case you should define your default route {controller}/{action}/{id}and put a constraint on it. Probably related to controller names or maybe even actions. Then put the catch all one after it and it should work just fine.
在您的情况下,您应该定义默认路由{controller}/{action}/{id}并对其施加约束。可能与控制器名称甚至动作有关。然后把所有的捕获放在它后面,它应该可以正常工作。
So when someone would request a resource that fails a constraint the catch-all route would match the request.
因此,当有人请求未通过约束的资源时,catch-all 路由将匹配请求。
So. Define your default route with route constraints first and then the catch all route after it:
所以。首先使用路由约束定义默认路由,然后在它之后捕获所有路由:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "Home|Settings|General|..." } // this is basically a regular expression
);
routes.MapRoute(
"NotFound",
"{*url}",
new { controller = "Error", action = "PageNotFound" }
);
回答by Praveen Prasad
//this catches all requests
routes.MapRoute(
"Error",
"{*.}",
new { controller = "PublicDisplay", action = "Error404" }
);
add this route at the end the routes table
在路由表的末尾添加这条路由
回答by Haacked
Ah, the problem is your default route catches all 3 segment URLs. The issue here is that Routing runs way before we determine who is going to handle the request. Thus any three segment URL will match the default route, even if it ends up later that there's no controller to handle it.
啊,问题是您的默认路由会捕获所有 3 个段 URL。这里的问题是 Routing 在我们确定谁将处理请求之前运行。因此,任何三段 URL 都将匹配默认路由,即使后来没有控制器来处理它。
One thing you can do is on your controller override the HandleMissingAction method. You should also use the tag to catch all 404 issues.
您可以做的一件事是在您的控制器上覆盖 HandleMissingAction 方法。您还应该使用标签来捕获所有 404 问题。
回答by Dustin Laine
Well, what I have found is that there is no good way to do this. I have set the redirectModeproperty of the customErrorsto ResponseRewrite.
好吧,我发现没有好的方法可以做到这一点。我已将 的redirectMode属性设置customErrors为ResponseRewrite。
<customErrors mode="On" defaultRedirect="~/Shared/Error" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="~/Shared/PageNotFound"/>
</customErrors>
This gives me the sought after behavior, but does not display the formatted page.
这给了我追捧的行为,但不显示格式化的页面。
To me this is poorly done, as far as SEO goes. However, I feel there is a solution that I am missing as SO does exactly what I want to happen. The URL remains on the failed page and throws a 404. Inspect stackoverflow.com/fail in Firebug.
对我来说,就 SEO 而言,这做得不好。但是,我觉得我缺少一个解决方案,因为 SO 正是我想要发生的事情。URL 保留在失败的页面上并抛出 404。检查 Firebug 中的 stackoverflow.com/fail。
回答by Chris Halcrow
I would recommend this as the most readable version. You need this in your RouteConfig.cs, and a controller called ErrorController.cs, containing an action 'PageNotFound'. This can return a view. Create a PageNotFound.cshtml, and it'll be returned in response to the 404:
我会推荐它作为最易读的版本。您需要在 RouteConfig.cs 和一个名为 ErrorController.cs 的控制器中使用它,其中包含一个操作“PageNotFound”。这可以返回一个视图。创建一个 PageNotFound.cshtml,它会在响应 404 时返回:
routes.MapRoute(
name: "PageNotFound",
url: "{*url}",
defaults: new { controller = "Error", action = "PageNotFound" }
);
How to read this:
如何阅读:
name: "PageNotFound"
= create a new route template, with the arbitrary name 'PageNotFound'
= 创建一个新的路由模板,使用任意名称“PageNotFound”
url:"{*url}"
= use this template to map all otherwise unhandled routes
= 使用此模板来映射所有其他未处理的路由
defaults: new { controller = "Error", action = "PageNotFound" }
= define the action that an incorrect path will map to (the 'PageNotFound' Action Method in the Error controller). This is needed since an incorrectly entered path will not obviously not map to any action method
= 定义错误路径将映射到的操作(错误控制器中的“PageNotFound”操作方法)。这是必需的,因为错误输入的路径显然不会映射到任何操作方法
回答by Ostati
If you're looking for ASP.NET Core catch all routes and searching Google for asp.net core catch all routebrings you here:
如果您正在寻找 ASP.NET Core,请捕获所有路线并在 Google 上搜索asp.net core catch all route将您带到这里:
回答by Marcus10110
My Solution is 2 steps.
我的解决方案是 2 个步骤。
I originally solved this problem by adding this function to my Global.asax.cs file:
我最初通过将此函数添加到我的 Global.asax.cs 文件来解决这个问题:
protected void Application_Error(Object sender, EventArgs e)
Where I tried casting Server.GetLastError() to a HttpException, and then checked GetHttpCode. This solution is detailed here:
我尝试将 Server.GetLastError() 转换为 HttpException,然后检查 GetHttpCode。此处详细介绍了此解决方案:
ASP.NET MVC Custom Error Handling Application_Error Global.asax?
ASP.NET MVC 自定义错误处理 Application_Error Global.asax?
This isn't the original source where I got the code. However, this only catches 404 errors which have already been routed. In my case, that ment any 2 level URL.
这不是我获得代码的原始来源。但是,这只捕获已路由的 404 错误。就我而言,这意味着任何 2 级 URL。
for instance, these URLs would display the 404 page:
例如,这些 URL 将显示 404 页面:
www.site.com/blah
www.site.com/blah
www.site.com/blah/blah
www.site.com/blah/blah
however, www.site.com/blah/blah/blah would simply say page could not be found. Adding your catch all route AFTER all of my other routes solved this:
但是,www.site.com/blah/blah/blah 只会说找不到页面。在我的所有其他路线解决了这个问题之后添加你的全部路线:
routes.MapRoute(
"NotFound",
"{*url}",
new { controller = "Errors", action = "Http404" }
);
However, the NotFound route does not seem to route requests which have file extensions. This does work when they are captured by different routes.
但是, NotFound 路由似乎不会路由具有文件扩展名的请求。当它们被不同的路线捕获时,这确实有效。
回答by Wyatt Barnett
You are probably better off configuring the 404 error document in the section of the configuration then restoring the default route.
您最好在配置部分配置404错误文档,然后恢复默认路由。
FWIW, I think the default route requirement is retarded too.
FWIW,我认为默认路由要求也被延迟了。

