[.Net Core] Multi language

Bạn có nhu cầu sử dụng đa ngôn ngữ trong .Net Core API của mình? Hãy tham khảo ví dụ sau

1. Register localize support in 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 = "Languages";
            });
        }

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

2. Tạo folder và tạo file có cấu trúc như sau

3. Tạo class LocalizerService

public class LocalizerService
    {
        private readonly IStringLocalizer _localizer;
        private readonly IHttpContextAccessor _contextAccessor;

        public LocalizerService(IStringLocalizerFactory factory, 
            IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
            string header = _contextAccessor.HttpContext.Request.Headers["Language"];   
            
            var specifiedCulture = new CultureInfo(header);
            CultureInfo.CurrentCulture = specifiedCulture;
            CultureInfo.CurrentUICulture = specifiedCulture;
            var options = Options.Create(new LocalizationOptions());
            factory = new ResourceManagerStringLocalizerFactory(options, new LoggerFactory());
            var localizer = new StringLocalizer<Translate>(factory);
            _localizer = localizer;
        }

        public string this[string key] => _localizer[key].Value;

        public LocalizedString GetLocalizedString(string key)
        {
            return _localizer[key];
        }
    }

4. DI trong startup.cs

services.AddScoped<LocalizerService>();

5. Sử dụng trong controller

public class TestController : BaseController
    {
        private readonly LocalizerService _localizer;

        public TestController(
            LocalizerService localizer)
        {
            _localizer = localizer;
        }

        public async Task<IActionResult> Test()
        {
             return Ok(_localizer["Hello"]);
        }

F G+ T

tuandph

Khởi đầu với .NET từ năm 2013 đến nay. Hiện tại mình đang làm full-stack developer. Yêu thích lập trình & chia sẽ kiến thức. Thời gian rảnh thường làm những tool vui vui và viết lách kể lệ sự đời.