从控制器设置默认区域性

从控制器设置默认区域性

本文介绍了ASP.Net Core:从控制器设置默认区域性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的ASP.Net Core Web API项目中设置本地化.

I am trying to set up localization in my ASP.Net Core Web API project.

我做了一些研究,并且了解到本地化中间件具有预定义的请求文化提供程序(在我的情况下这是不可接受的),因此我需要编写一个自定义请求文化提供程序,例如

I did some research and understand that there is a localization middleware with predefined request culture providers (which in my case are not acceptable), so I need to write a custom request culture provider, something like

public class CustomCultureProvider : RequestCultureProvider
{
    public override async Task<ProviderCultureResult> ChangeCulture(HttpContext httpContext)
    {
        // Return a culture...
        return new ProviderCultureResult("en-US");
    }
}

我不了解的是如何从控制器(即调用端点)时更改区域性.

What I don't understand is how I can change the culture from a controller, that is, when an endpoint is called.

推荐答案

这是asp.net core 3.x的有效演示,它可以切换三种语言以显示响应:

Here is a working demo for asp.net core 3.x that could switch three languages to display the response:

1.自定义RouteDataRequestCultureProvider:

public class CustomRouteDataRequestCultureProvider : RequestCultureProvider
{
    public int IndexOfCulture;
    public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException(nameof(httpContext));
        string culture = null;


        var twoLetterCultureName = httpContext.Request.Path.Value.Split('/')[IndexOfCulture]?.ToString();

        if (twoLetterCultureName == "de" )
            culture = twoLetterCultureName;
        else if (twoLetterCultureName == "fr")
            culture = twoLetterCultureName;
        else if(twoLetterCultureName =="en")
            culture = twoLetterCultureName;

        if (culture == null)
            return NullProviderCultureResult;

        var providerResultCulture = new ProviderCultureResult(culture);

        return Task.FromResult(providerResultCulture);
    }
}

2.Startup.cs:

2.Startup.cs:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddControllers().AddViewLocalization(
    LanguageViewLocationExpanderFormat.Suffix,
    opts => { opts.ResourcesPath = "Resources"; })
    .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(options => {
        var supportedCultures = new CultureInfo[] {
            new CultureInfo("en"),
            new CultureInfo("de"),
            new CultureInfo("fr")
    };
        options.DefaultRequestCulture = new RequestCulture("en");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;

        options.RequestCultureProviders = new[]{ new CustomRouteDataRequestCultureProvider{
            IndexOfCulture=1,
        }};
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(options.Value);

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapControllerRoute("LocalizedDefault", "{culture:cultrue}/{controller=Home}/{action=Index}/{id?}");

    });
}

测试项目:

1.创建文件夹Resources/Controllers.

2.创建资源文件,并命名为[ControllerName].[Language].resx,如下所示:

2.Create resource file and named as [ControllerName].[Language].resx like below:

3.编辑资源文件的内容(即ValuesController.de.resx):

3.Edit the content of resource file(i.e. ValuesController.de.resx):

4.创建一个控制器:

4.Create a Controller:

[Route("{culture?}/api/[controller]")]
public class ValuesController : Controller
{
    private readonly IStringLocalizer<ValuesController> _localizer;

    public ValuesController(IStringLocalizer<ValuesController> localizer)
    {
        _localizer = localizer;
    }
    // GET: api/<controller>
    [HttpGet]
    public IActionResult Get()
    {
        return new ObjectResult(_localizer["Hi"]);
    }
}

结果:

这篇关于ASP.Net Core:从控制器设置默认区域性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 03:30