【问题标题】:localization in asp.net core 2.0 razor web application without mvc没有 mvc 的 asp.net core 2.0 razor web 应用程序中的本地化
【发布时间】:2018-09-11 17:05:05
【问题描述】:

我发现的每个示例,包括位于https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-2.1 的有关本地化的官方 Microsoft 文档,都使用控制器来执行设置和保存所需文化的操作。我的 ASP.NET Core 2.1 Web 应用程序不是 MVC,因此没有控制器。我尝试了几种方法来解决这个问题,包括在我的项目中添加一个虚拟控制器,但我仍然无法让文化开关工作。

我的 Startup 类的 Configure 方法包含以下代码:

            var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("hi-IN")
        };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture(DefaultCulture.Name),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });
        app.UseHttpsRedirection();
        app.UseAuthentication();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseMvc();

ConfigureServices 方法包含以下代码:

            // Add the localization services to the services container
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        // Add MVC Services to the Services Collection.
        services.AddMvc()
            // Add support for finding localized views, based on file name suffix, e.g. Index.fr.cshtml
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            // Add support for localizing strings in data annotations (e.g. validation messages) via the
            // IStringLocalizer abstractions.
            .AddDataAnnotationsLocalization();

        // Configure supported cultures and localization options
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("hi-IN")
        };

        services.Configure<RequestLocalizationOptions>(options =>
        {
            // State what the default culture for your application is. This will be used if no specific culture
            // can be determined for a given request.
            options.DefaultRequestCulture = new RequestCulture(DefaultCulture.Name, DefaultCulture.Name);

            // You must explicitly state which cultures your application supports.
            // These are the cultures the app supports for formatting numbers, dates, etc.
            options.SupportedCultures = supportedCultures;

            // These are the cultures the app supports for UI strings, i.e. we have localized resources for.
            options.SupportedUICultures = supportedCultures;
        });

        // Register the email service used for "contacts".
        services.AddSingleton<IEmailSender, EmailSender>();

        // Configure startup to use the SendGrid options.
        services.Configure<AuthMessageSenderOptions>(Configuration);

        // Add cross-origin resource sharing services to the specified IServiceCollection.
        //
        // The Policy specifed as an option will allow any method.
        services.AddCors(options => options.AddPolicy("CorsPolicy", b => b.AllowAnyMethod()));

而 DefaultCulture 是:

DefaultCulture = new CultureInfo(Configuration["Localization:DefaultCulture"]); 

其中设置文件包含字符串“en-US”。

然后我使用本地化文档示例中的 _SelectLanguagePartial.cshtml 代码:

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
<form id="selectLanguage" asp-controller="Home" 
      asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" 
      method="post" class="form-horizontal" role="form">
    <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label> 
    <select name="culture" onchange="this.form.submit();" asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems"></select>
</form>

首先,没有控制器。如何在非 MVC ASP.NET Core Web 应用中实现此功能?

【问题讨论】:

  • 你的问题真的没有意义。您的网络应用需要 something 来处理路由。那是控制器或 Razor 页面。无论哪种情况,文档采用的方法大致相同。

标签: asp.net razor asp.net-core localization asp.net-core-localization


【解决方案1】:

您不必使用控制器,最近我发布了使用 ASP.NET Core Razor Pages 开发多文化 Web 应用程序的分步教程;你可以在这里找到它:

http://www.ziyad.info/en/articles/10-Developing_Multicultural_Web_Application

我使用 rout 值方法,但您可以将其扩展为使用查询字符串、cookie 或接受的标头值进行文化选择。

在网站上你可以在github上看到一个live demo和项目源代码链接。

此外,您可能还需要检查本地化身份错误消息:

http://ziyad.info/en/articles/20-Localizing_Identity_Error_Messages

希望对你有帮助:)

[更新]

我提供的示例是使用共享资源文件。如果您想使用视图相关的资源文件方法,请在“资源”文件夹中为每个视图/文化创建资源文件,并保持资源的文件夹结构与其相关视图相似。

例如,如果我们在 pages 文件夹中有一个名为“MyView”的视图:

页面/MyView.cshtml

资源文件应如下所示:

资源/页面/MyView.tr-TR.resx

资源/页面/MyView.ar-SY.resx

资源/页面/MyView.hi-IN.resx

要在视图中使用本地化注入 IViewLocalizer:

@using Microsoft.AspNetCore.Mvc.Localization    
@inject IViewLocalizer _loc

<h4>@_loc["My view title"]</h4>

对于 ViewModel/DataAnnotations,为每种文化创建另一个资源文件:

查看模型:

页面/MyViewModel.cshtml.cs

资源文件名:

资源/页面/MyViewModel.tr-TR.resx

资源/页面/MyViewModel.ar-SY.resx

资源/页面/MyViewModel.hi-IN.resx

用相关的模型属性显示名称和数据注释消息填充资源文件,然后通过清除DataAnnotations的共享资源代码并保持其无参数来修改startup.cs文件:

services.AddMvc()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddViewLocalization(o=>o.ResourcesPath = "Resources")
                
                // Option A: use this for localization with shared resource
                /*
                .AddDataAnnotationsLocalization(o=> {
                    var type = typeof(ViewResource);
                    var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
                    var factory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
                    var localizer = factory.Create("ViewResource", assemblyName.Name);
                    o.DataAnnotationLocalizerProvider = (t, f) => localizer;
                })
                */

                // Option B: use this for localization by view specific resource
                .AddDataAnnotationsLocalization() 

                .AddRazorPagesOptions(o => {
                    o.Conventions.Add(new CultureTemplateRouteModelConvention());
                });

顺便说一句,我更新了 GitHub 示例,现在它包含使用视图特定资源文件本地化的“AnotherPage”视图。

【讨论】:

  • 嘿 Laz,我一直在查看您的 MyTrips 存储库中的代码,它绝对非常好。但是有一件事 - 我看到您正在使用同名且位于同一文件夹中的资源文件,例如 ViewResource.es.resx。由于我的应用程序包含的页面数量,我使用每个页面方法 1 个资源文件。我似乎找不到正确的位置来修改 CultureLocalizer 类或 Startup 类的 ConfigureServices 中的代码。你能给我一些关于如何修改代码以使用基于页面(视图)的资源的指示吗?
  • 嗨@JNickVA1,为了使用查看特定资源文件,您只需要进行一些修改,请在评论中查看...
猜你喜欢
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 2011-07-09
  • 2018-07-23
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多