Ehsan Ghanbari

Experience, DotNet, Solutions

Localization in asp.net core API for every request

Recently I was tackling a problem with localization in asp.net core. I wanted to get the culture in every request from API and respond based on the requested culture. So I created the following middleware as it's not possible to have access HttpContext in asp.net core by default.

 

public class CultureValidationMiddleware

    {

        private readonly RequestDelegate _next;

 

        public CultureValidationMiddleware(RequestDelegate next)

        {

            _next = next;

        }

 

        public async Task Invoke(HttpContext httpContext)

        {

            IHeaderDictionary headers = httpContext.Request.Headers;

            var culture = CultureManager.GetImplementedCulture(headers["culture"]);

          

            var supportedCultures = CultureManager.GetSupportedCultures();

            var localizationOptions = new RequestLocalizationOptions

            {

                DefaultRequestCulture = new RequestCulture(culture),

                SupportedCultures = supportedCultures,

                SupportedUICultures = supportedCultures

            };

        

            await _next.Invoke(httpContext);

        }

    }

 

In order to use the above middleware I had to create an extension method like below:

 

  

public static class ApplicationBuilderExtensions

    {

        public static IApplicationBuilder SetCultureValue(this IApplicationBuilder app)

        {

            return app.UseMiddleware<CultureValidationMiddleware>();

        }

    }

 

The point was this that I couldn’t use  app.UseRequestLocalization(); in the startup as I wanted to get the culture in every request! After tackling a lot I found another way to solve the issue.

 

  public class UserProfileRequestCultureProvider : RequestCultureProvider

    {

        public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)

        {

            if (httpContext == null)

            {

                throw new ArgumentNullException(nameof(httpContext));

            }

 

            IHeaderDictionary headers = httpContext.Request.Headers;

            var culture = CultureManager.GetImplementedCulture(headers["culture"]);

 

            return Task.FromResult(new ProviderCultureResult(culture));

        }

    }

 

By configuring the above provider in services of Startup class I solved the issue!

 

services.Configure<RequestLocalizationOptions>(options =>

            {

                options.DefaultRequestCulture = new RequestCulture(culture: "fa-ir");

                options.SupportedCultures = supportedCultures;

                options.SupportedUICultures = supportedCultures;

                options.RequestCultureProviders.Clear();

                options.RequestCultureProviders.Add(new UserProfileRequestCultureProvider());

            });

 

If you know a better way, please help me!

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to query over Icollection<> of a type with linq
How to use PagedList In asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
Using Generic type for type casting in F#
comments powered by Disqus