【问题标题】:ASP.NET Core 1.0 Application resources namingASP.NET Core 1.0 应用程序资源命名
【发布时间】:2018-02-12 00:01:30
【问题描述】:

我正在尝试在 ASP.NET Core 1.0 Web 应用程序中为我的 MVC 视图本地化。

到目前为止,我已经使用 ConfigureServices 方法设置了我的 Startup.cs 文件:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRouting(configureOptions => configureOptions.LowercaseUrls = true);
        services.AddMvc()
            .AddViewLocalization(setupAction => setupAction.ResourcesPath = "Resources")
            .AddDataAnnotationsLocalization();
    }

然后是我的Configure 方法:

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        loggerFactory.MinimumLevel = LogLevel.Information;
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        CultureInfo defaultCulture = new CultureInfo("en");
        List<CultureInfo> supportedCultures = new List<CultureInfo>
        {
            defaultCulture,
            new CultureInfo("fr")
        };

        RequestLocalizationOptions requestLocalizationOptions = new RequestLocalizationOptions
        {
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures,
        };

        RequestCulture defaultRequestCulture = new RequestCulture(defaultCulture);
        //Insert this at the beginning of the list since providers are evaluated in order until one returns a not null result
        requestLocalizationOptions.RequestCultureProviders.Insert(0, new UrlCultureProvider());
        app.UseRequestLocalization(requestLocalizationOptions, defaultRequestCulture);

        app.UseIISPlatformHandler();
        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "defaultWithCulture",
                template: "{culture}/{controller}/{action}/{id?}",
                defaults: new { culture = "en", controller = "Home", action = "Index" },
                constraints: new { culture = "en|fr" });
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id?}",
                defaults: new { culture = "en", controller = "Home", action = "Index" });
        });
        app.UseStatusCodePages();
    }

最后是我的 UrlCultureProvider 类,它可以帮助我在 url 中提供文化时设置文化:

public class UrlCultureProvider : IRequestCultureProvider
{
    public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {

        var url = httpContext.Request.Path;

        //Quick and dirty parsing of language from url path, which looks like "/api/de-DE/home"
        //This wont be needed in RC2 since an extension method GetRouteData has been added to HttpContext
        //which means we could just get the the "language" parameter from the route data
        var parts = httpContext.Request.Path.Value.Split('/');
        if (parts.Length < 2)
        {
            return Task.FromResult<ProviderCultureResult>(null);
        }
        var hasCulture = Regex.IsMatch(parts[1], @"^[a-z]{2}$");

        if (!hasCulture)
        {
            return Task.FromResult<ProviderCultureResult>(null);
        }

        var culture = parts[1];
        return Task.FromResult(new ProviderCultureResult(culture));
    }
}

如果它出现在 url 中,则文化设置为 fr 或 en。 比我的“资源”文件夹中有两个资源文件:

Views.Home.Index.cshtml.resx

Views.Home.Index.cshtml.fr.resx

在我的_ViewImports.cshtml 文件中,我有这个代码:

@using Microsoft.AspNet.Mvc.Localization
@inject IViewLocalizer Localization

最后,我的索引视图中有一个资源调用:

@Localization["Test"]

我使用“en”文化而不是“fr”文化。

你知道那里发生了什么吗?

谢谢。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc


    【解决方案1】:

    我确定这已经过时了,但以防万一它对某人有所帮助,我认为问题可能是您不需要在 resx 文件名中包含 .cshtml。这或许可以解释为什么它只查找默认文本。

    当您使用@Localizer["Some text"] 时,它会在相关资源文件中查找键“Some text”,但如果找不到(或找不到 resx 文件),它将使用密钥作为默认文本。

    干杯

    【讨论】:

      【解决方案2】:

      经过一番调查,Visual Studio 目前似乎存在一个错误,在 IDE 上进行调试时不允许发现资源文件 (.Resx)。 这个问题在这里解决:

      https://github.com/aspnet/Mvc/issues/3846

      希望这个错误将在 ASP.NET Core 1.0 RC2 中得到修复。

      无论如何,当我部署到 azure 时,可以正确找到资源文件。

      【讨论】:

        【解决方案3】:

        据我所知,您的项目几乎没有命名错误。

        首先你不应该使用.cshtml 扩展名,它们应该是这样的:

        Views.Home.Index.en.resx
        Views.Home.Index.fr.resx
        

        如果你喜欢为_ViewImports.cshtml 使用本地化,他们的名字应该是

        Views.Shared._ViewImports.en.resx
        Views.Shared._ViewImports.fr.resx
        

        我认为很可能_ViewImports.cshtml 在“共享”文件夹中,我使用“共享”进行命名。

        最后,如果您必须为每个 .cshtml 分别注入 IViewLocalizer

        你可以阅读微软的详细documentation

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多