C# MVC错误页控制器和自定义路由
我已修改我的路由,以便在URL中包含区域性C# MVC错误页控制器和自定义路由,c#,asp.net,asp.net-mvc,routing,asp.net-mvc-routing,C#,Asp.net,Asp.net Mvc,Routing,Asp.net Mvc Routing,我已修改我的路由,以便在URL中包含区域性 routes.MapRoute( name: "Default", url: "{culture}/{controller}/{action}/{id}", defaults: new { culture = "en-GB", controller = "StyleGuide", action = "Template", id = UrlParameter.Optional },
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = "en-GB", controller = "StyleGuide", action = "Template", id = UrlParameter.Optional },
constraints: new { culture = @"[a-z]{2}-[A-Z]{2}" }
);
我还创建了ErrorController
,并在Web.config
中定义了我的错误页面:
<customErrors mode="On" defaultRedirect="~/Error/Index">
<error statusCode="404" redirect="~/Error/NotFound"/>
</customErrors>
我也在使用mvcSiteMapProvider,因此我已经包含了我的新错误页面,并且能够通过菜单访问它们,因为它使用了一个包含我的区域性的URL:localhost/en GB/error/NotFound
引发异常时,找不到错误页,因为Web.Config
中定义的重定向中缺少区域性
重定向到错误页面时,如何包含区域性?这是一篇很好的文章,介绍了ASP.NET MVC中错误处理方法的可能性和局限性: 如果不需要控制器或操作级异常处理,可以在
Application\u error
事件中执行错误处理。您可以在web.config中关闭自定义错误,并在此事件中执行日志记录和错误处理(包括重定向到正确的页面)
类似于此:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
string action = string.Empty;
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = "NotFound";
break;
//TODO: handle other codes
default:
action = "general-error";
break;
}
}
else
{
//TODO: Define action for other exception types
action = "general-error";
}
Server.ClearError();
string culture = Thread.CurrentThread.CurrentCulture.Name;
Exception exception = Server.GetLastError();
Response.Redirect(String.Format("~/{0}/error/{1}", culture, action));
}
我很快会看一看,然后再给你回复-谢谢你的回答!谢谢你这么快回复他们