如何将 MVC URL 错误路由到我们选择的视图?
如果我们使用这个标准路由:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
在带有 MVC 2 设置的 Windows 2008 IIS7 中,我们转到这里:
"http://www.mywebsite.com/SomePageThatDoesNotExist.aspx"
然后在 Application_Error 方法下,我们得到这样的:
protected void Application_Error(object sender, EventArgs e)
{
Response.Clear();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
}
我们没有得到我们期望的路由和页面,而是得到一个令人讨厌的 404 服务器错误页面。知道如何捕获 url 错误并将其定向到我们选择的页面吗?
If we use this standard route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
and within Windows 2008 IIS7 with MVC 2 setup we go to here:
"http://www.mywebsite.com/SomePageThatDoesNotExist.aspx"
and then under the Application_Error method we have this:
protected void Application_Error(object sender, EventArgs e)
{
Response.Clear();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(
new HttpContextWrapper(Context), routeData));
}
Instead of getting a route and a page we expect, we get a nasty 404 Server error page. Any idea how to capture url errors and direct them to a page of our choice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
MVC 有 HandleErrorAttribute。您可以将其自定义为仅处理 404 或其他类型的错误。
您可以将不同类型的异常与不同的视图相关联。在上面的示例中,当操作抛出 ResourceNotFoundException 时,它将呈现 ResourceNotFound 视图。
这是链接< /a> 关于如何处理404错误,作者提供了几种处理方法。
MVC has HandleErrorAttribute. You can customize it to handle only 404 or other types of error.
You can associate different type of exception with different views. In the above example, when the action throw ResourceNotFoundException, it will render ResourceNotFound view.
Here is a link on how to handle 404 errors, the author provided a couple of ways to handle it.
您可以像这样在 web.config 中执行此操作。
You can do it in the web.config like this.