Localization of ASP.NET Core WebAPI (single resource file)

Localization of ASP.NET Core WebAPI (single resource file)

Microsoft's default method is that one class corresponds to multiple resource files, which is quite troublesome to use. This article introduces the use of single resource files, that is, all classes of the entire project correspond to a set of multi-language resource files.

最后更新 6/22/2022 10:37 PM
HueiFeng
预计阅读 2 分钟
分类
ASP.NET Core
标签
.NET C# ASP.NET Core Web API localization

在 Startup ConfigureServices 注册本地化所需要的服务AddLocalizationConfigure<RequestLocalizationOptions>

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization();
    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new List<CultureInfo>
        {
            new CultureInfo("en-us"),
            new CultureInfo("zh-cn")
        };

        options.DefaultRequestCulture = new RequestCulture(culture: "en-us", uiCulture: "en-us");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
        options.RequestCultureProviders = new IRequestCultureProvider[] { new RouteDataRequestCultureProvider { IndexOfCulture = 1, IndexofUiCulture = 1 } };
    });
    services.Configure<RouteOptions>(options =>
    {
        options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint));
    });
    services.AddControllers();
}

在 Startup.cs 类的 Configure 方法中添加请求本地化中间件。

var localizeOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
            app.UseRequestLocalization(localizeOptions.Value);

RequestCultureProvider 它使用简单的委托来确定当前的本地化区域性,当然我们还可以通过RequestCultureProvider自定义源的请求区域信息比如说配置文件或者数据库都是可以的.或者说我们可以选用默认的一些方式让我们去获取到当前区域.

ASP.NET Core localization provides us with four ways by default to determine the current culture of the request being executed:

  • QueryStringRequestCultureProvider
  • CookieRequestCultureProvider
  • AcceptLanguageHeaderRequestCultureProvider
  • CustomRequestCultureProvider

As shown below, I will use routing to determine the current area

public class RouteDataRequestCultureProvider : RequestCultureProvider
{
    public int IndexOfCulture;
    public int IndexofUiCulture;

    public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException(nameof(httpContext));
        string uiCulture;

        string culture = uiCulture = httpContext.Request.Path.Value.Split('/')[IndexOfCulture];

        var providerResultCulture = new ProviderCultureResult(culture, uiCulture);

        return Task.FromResult(providerResultCulture);
    }
}

Use the following code fragment to implement IRouteConstraint to restrict routes accordingly

public class LanguageRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {

        if (!values.ContainsKey("culture"))
            return false;

        var culture = values["culture"].ToString();
        return culture == "en-us" || culture == "zh-cn";
    }
}

Add area resource files

[Route("{culture:culture}/[controller]")]
[ApiController]
public class HomeController : ControllerBase
{
    private readonly IStringLocalizer<Resource> localizer;
    public HomeController(IStringLocalizer<Resource> localizer)
    {
        this.localizer = localizer;
    }
    public string Get()
    {
        return localizer["Home"];
    }
}

Reference:https://github.com/hueifeng/BlogSample/tree/master/src/LocalizationSingleResx

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 4/13/2022

ASP.NET Core WebApi returns results Unified packaging practices

When WebApi unifies the return of results, I also thought further. First, how to better limit the return of unified formats, and secondly, the packaging of results must be simpler and more powerful. Through constant thinking and improvement, I finally had preliminary results, so I shared them. There was no end to learning and there was no end to thinking. I hope that I can share encouragement with you in this way.

继续阅读