首先,看一下这个答案有关通过 URL 本地化您的网站的信息。
Next, <customErrors>
是 ASP.NET 错误消息的总括。但一般来说,您可以通过使用包罗万象的路由来控制 ASP.NET MVC 中的 404(路由未命中)。在这种情况下,您可以简单地本地化 catch-all 路由并在 web.config 中删除此配置。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Localized-Default",
url: "{lang}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { lang = new CultureConstraint(defaultCulture: "fa", pattern: "[a-z]{2}") }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { lang = "fa", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// Catch-all route (for routing misses)
routes.MapRoute(
name: "Localized-404",
url: "{lang}/{*url}",
defaults: new { controller = "Error", action = "PageNotFound" },
constraints: new { lang = new CultureConstraint(defaultCulture: "fa", pattern: "[a-z]{2}") }
);
routes.MapRoute(
name: "Default-404",
url: "{*url}",
defaults: new { lang = "fa", controller = "Error", action = "PageNotFound" }
);
}
}
错误控制器
public class ErrorController : Controller
{
public ActionResult PageNotFound()
{
Response.CacheControl = "no-cache";
Response.StatusCode = (int)HttpStatusCode.NotFound;
return View();
}
}
这可以解决 ASP.NET 中的路由缺失问题。对于那些不使用 ASP.NET 的用户(假设您使用 IIS 进行托管),您应该使用<httpErrors>
web.config 部分而不是<customErrors>
. <httpErrors>
可以通过本地化prefixLanguageFilePath setting.
可选字符串属性。
指定生成自定义错误的路径时的初始路径段。该段出现在自定义错误路径的特定于语言的部分之前。例如,在路径 C:\Inetpub\Custerr\en-us\404.htm 中,C:\Inetpub\Custerr 是前缀LanguageFilePath。
<configuration>
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly" defaultResponseMode="File" >
<remove statusCode="404" />
<error statusCode="404"
prefixLanguageFilePath="C:\Contoso\Content\errors"
path="404.htm" />
</httpErrors>
</system.webServer>
</configuration>
这意味着您需要设置带有语言前缀的文件结构,并使用静态文件作为目标。
C:\Contoso\Content\errors\fa\404.htm
C:\Contoso\Content\errors\en\404.htm
AFAIK,不幸的是,这意味着您需要在这些位置拥有物理文件。但是,您可以将这些页面的内容设置为执行元刷新重定向andJavaScript 重定向到正确的控制器操作。
<html>
<head>
<title>404 Not Found</title>
<meta http-equiv="refresh" content="1;http://www.example.com/fa/Error/PageNotFound" />
</head>
<body>
<!-- Add localized message (for those browsers that don't redirect). -->
<script>
//<!--
setTimeout(function () {
window.location = "http://www.example.com/fa/Error/PageNotFound";
}, 1000);
//-->
</script>
</body>
</html>