ASP.NET Core 1.0应用程序资源命名

时间:2016-04-25 21:27:27

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

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

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

    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课程帮助我在网址中提供文化时设置文化:

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));
    }
}

如果文化在网址中显示,则将文化设置为fr或en。 我的'Resources'文件夹上有两个资源文件:

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”文化。

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

谢谢。

3 个答案:

答案 0 :(得分:1)

我确定现在已经过时了但是为了防止有人,我认为问题可能是您不需要在resx文件名中包含.cshtml。这可能解释了为什么它只找到默认文本。

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

干杯

答案 1 :(得分:0)

经过一些调查后,看起来Visual Studio目前存在一个错误,该错误禁止在IDE上进行调试时发现资源文件(.Resx)。 这个问题在这里得到解决:

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

希望在ASP.NET Core 1.0 RC2中修复此错误。

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

答案 2 :(得分:0)

正如我所看到的,项目命名错误很少。

首先,您不应该使用.cshtml扩展名:

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

如果您想使用本地化_ViewImports.cshtml,他们的名字应为

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

我认为很可能是{Shared}文件夹中的_ViewImports.cshtml,我使用'Shared'来命名。

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

您可以阅读Microsoft的详细documentation