asp.net-mvc 如何制作一个捕获所有路由来处理 ASP.NET MVC 的“404 页面未找到”查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/310580/
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
How to make a catch all route to handle '404 page not found' queries for ASP.NET MVC?
提问by Pure.Krome
Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?
是否可以创建一个最终路由来捕获所有 .. 并将用户退回到 ASP.NET MVC 中的 404 视图?
NOTE: I don't want to set this up in my IIS settings.
注意:我不想在我的 IIS 设置中进行设置。
回答by Pure.Krome
Found the answer myself.
自己找到了答案。
Richard Dingwallhas 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 :)
理查德·丁沃尔 (Richard Dingwall) 发表了一篇出色的文章,介绍了各种策略。我特别喜欢 FilterAttribute 解决方案。我不喜欢在 willy nilly 周围抛出异常,所以我会看看我是否可以改进:)
For the global.asax, just add this code as your last route to register:
对于 global.asax,只需将此代码添加为您最后注册的路线:
routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "StaticContent", action = "PageNotFound" }
);
回答by smdrager
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.
我通过创建一个返回本文中的视图的 ErrorController 来使我的错误处理工作。我还必须将“Catch All”添加到 global.asax 中的路由。
如果它不在 Web.config 中,我看不到它如何进入任何这些错误页面?我的 Web.config 必须指定:
customErrors mode="On" defaultRedirect="~/Error/Unknown"然后我还补充道:
error statusCode="404" redirect="~/Error/NotFound"希望这可以帮助。
I love this way now because it is so simple:
我现在喜欢这种方式,因为它很简单:
<customErrors mode="On" defaultRedirect="~/Error/" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="~/Error/PageNotFound/" />
</customErrors>
回答by MSDs
Also you can handle NOT FOUND error in Global.asax.cs as below
您也可以在 Global.asax.cs 中处理 NOT FOUND 错误,如下所示
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
}
}
回答by Vicky
Add this lines under your project root web.config File.
在您的项目根 web.config 文件下添加此行。
<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>
回答by Paco
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.
当你想抓住它时,我不知道任何其他方式然后编辑你的网络配置。
回答by Edward Brey
An alternative to creating a catch-all route is to add an Application_EndRequestmethod to your MvcApplicationper Marco's Better-Than-Unicorns MVC 404 Answer.
创建包罗万象的路线的另一种Application_EndRequest方法是向您的MvcApplication每个Marco 的 Better-Than-Unicorns MVC 404 Answer添加一个方法。
回答by solanki dev
Inside RouterConfig.csadd the follwing piece of code:
在里面RouterConfig.cs添加以下代码:
routes.MapRoute(
name: "Error",
url: "{id}",
defaults: new
{
controller = "Error",
action = "PageNotFound"
});
回答by Laxmeesh Joshi
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..
如果路由无法解析,那么 MVC 框架将通过 404 错误.. 最好的方法是使用异常过滤器......创建一个自定义异常过滤器并像这样制作..
public class RouteNotFoundAttribute : FilterAttribute, IExceptionFilter {
public void OnException(ExceptionContext filterContext) {
filterContext.Result = new RedirectResult("~/Content/RouteNotFound.html");
}
}

