asp.net-mvc - 在 MVC 中创建多语言未找到页面

标签 asp.net-mvc http-status-code-404 asp.net-mvc-routing multilingual

我们有一个多语言网站,其中包含四种语言的内容。我们在 url 的第一个添加的语言名称可以理解每种语言。
这是我们的 routeConfig.cs:

   routes.MapRoute(
            name: "Default",
            url: "{lang}/{controller}/{action}/{id}/{title}",
            defaults: new { lang = "fa", controller = "Home", action = "Index", id = UrlParameter.Optional,title = UrlParameter.Optional }

这是生成的网址:/en/ContactUs/Index

此外,在我们的 Controller 中,我们从 url 获取语言名称并根据它更改 currentCulture 和 currentUiCulture。
现在,我们希望在所有语言中都有一个未找到的页面。通常,为了实现它,我们添加一个错误 Controller 和一个 NotFound 操作和 View ,然后我们在 web.config 中添加此部分:
  <customErrors mode="On" defaultRedirect="error">
  <error statusCode="404" redirect="error/notfound" />
  <error statusCode="403" redirect="error/forbidden" />
</customErrors>

我们添加了一个 NotFound 页面,我们在其中使用 .resx 文件来制作 rtl/ltr 并以四种语言显示消息。
但这里的问题是,在多语言网站中,我们不允许使用“error/notfound”这个地址,因为其中没有语言名称,我们也不知道如何在 redirect="error/notfound"中添加语言名称在 web.config 文件中创建类似“en/error/notfound”或“fa/error/notfound”的内容。
每一个帮助将不胜感激

最佳答案

首先,看看this answer有关通过 URL 本地化站点的信息。
接下来,<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" }
        );
    }
}
错误 Controller
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 本地化.

Optional string attribute.

Specifies the initial path segment when generating the path for a custom error. This segment appears before the language-specific portion of the custom error path. For example, in the path C:\Inetpub\Custerr\en-us\404.htm, C:\Inetpub\Custerr is the prefixLanguageFilePath.

<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,不幸的是,这意味着您需要在这些位置拥有物理文件。但是,您可以将这些页面的内容设置为执行元刷新重定向和 JavaScript 重定向到正确的 Controller 操作。
<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>

关于asp.net-mvc - 在 MVC 中创建多语言未找到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34577151/

相关文章:

c# - Html.BeginForm 会在该区域后自动添加一个子文件夹

c# - 如何从数据列中获取数据

python - 哪个更好地测试 python 中的有效 url

c# - 使用静态类处理 session 数据

Javascript 404检查 anchor 标记点击

internet-explorer - 'pagerror.gif' 的意义?

asp.net-mvc - 在 ASP.Net MVC 中获取任何文件的完整 url

asp.net-mvc - asp.NET : Unknown length MVC paths

c# - 有没有什么可以将奥尔森时区列表缩减为用户界面可读的格式(就像谷歌日历一样)?

asp.net-mvc - ReturnUrl 指向 ActionResult