How to read Resource key and values based on the c

2019-08-21 04:26发布

I am working localization project and stuck in the middle when trying to read values from Resource file.

I have done all configurations as below.

Configure localization:

var supportedCultures = new List<CultureInfo>
        {
            new CultureInfo("en-US"),
            new CultureInfo("de-DE"),
            new CultureInfo("fr-FR")
        };
        services.Configure<RequestLocalizationOptions>(options =>
        {
            options.DefaultRequestCulture = new RequestCulture(supportedCultures[0]);
            options.SupportedCultures = supportedCultures;
            options.RequestCultureProviders.Insert(0, new CustomerCultureProvider());
        })

Configure the ASP.NET Core middleware

app.UseRequestLocalization();

Custom request culture provider

public class CustomerCultureProvider : RequestCultureProvider
{
    public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        await Task.Yield();

        return new ProviderCultureResult("de-DE");
    }
}

Below is my project structure:

enter image description here

I am trying to read the Resource Key "Name" in API endpoint as below:

[HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        var name = Employees.Name;
        return new string[] { name };
    }

If I set the culture de-DF, I should get the German translated text but it is not giving as expected.

My question, How can we get keys based on the culture we set in the startup? and How can I set the Resource path as my resource files in another project?

1条回答
甜甜的少女心
2楼-- · 2019-08-21 04:49

You need using one resource string for multiple classes so you need to create empty SharedResource class then register in Startup.cs like this

services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
        .AddDataAnnotationsLocalization(options => {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResource));
        });

services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[]
    {
        new CultureInfo(enUSCulture),
        new CultureInfo("fr")
    };

    options.DefaultRequestCulture = new RequestCulture(culture: enUSCulture, uiCulture: enUSCulture);
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;

    options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
    {
        // My custom request culture logic
        return new ProviderCultureResult("en");
    }));
});

Then you have to inject IViewLocalizer in your view like this

@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer // here
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

<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>
</div>

Please let me know if you still have problem

查看更多
登录 后发表回答