Pur*_*ome 49 asp.net-mvc routes http-status-code-404
是否有可能创建一个捕获所有的最终路由...并将用户弹回到ASP.NET MVC中的404视图?
注意:我不想在我的IIS设置中进行此设置.
Pur*_*ome 74
我自己找到了答案.
理查德·丁沃尔(Richard Dingwall)在各种策 我特别喜欢FilterAttribute解决方案.我不喜欢在willy nilly周围抛出异常,所以我会看看我是否可以改进:)
对于global.asax,只需添加此代码作为注册的最后一条路径:
routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "StaticContent", action = "PageNotFound" }
);
Run Code Online (Sandbox Code Playgroud)
smd*_*ger 20
这个问题首先出现,但更容易的答案出现在后来的问题中:
我通过创建一个返回本文中视图的ErrorController来使我的错误处理工作.我还必须在global.asax中添加"Catch All"到路由.
如果它不在Web.config中,我无法看到它将如何到达任何这些错误页面.?我的Web.config必须指定:
Run Code Online (Sandbox Code Playgroud)customErrors mode="On" defaultRedirect="~/Error/Unknown"
然后我还补充说:
Run Code Online (Sandbox Code Playgroud)error statusCode="404" redirect="~/Error/NotFound"
希望这可以帮助.
我现在喜欢这种方式,因为它很简单:
<customErrors mode="On" defaultRedirect="~/Error/" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="~/Error/PageNotFound/" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)
小智 6
您也可以如下处理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
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
87114 次 |
最近记录: |