Search code examples
angularmultilingualasp.net-core-2.2

asp.net core web api with angular 7 multi language support


I am developing an angular 7 application with asp.net core web API. My application is multi-language supported(English and Arabic). When the user selects a language from the angular application, I am saving his language preference in local storage. Now how to send the selected language to the web API, so that based upon the selected language I can return data from the server, and display the notification in his selected language from web API.


Solution

  • You'll have to make sure that language header Accept-Language is sent with each request to the server.

    Since there could be many APIs and making sure that selected language header is sent with each one could be a cumbersome task, make use of HttpInterceptor Angular feature. Something like this

    @Injectable()
    export class HTTPListener implements HttpInterceptor {
      constructor() {
      }
    
      intercept(
        req: HttpRequest<any>,
        next: HttpHandler
      ): Observable<HttpEvent<any>> {
    
        let languageRequest = req.clone({ setHeaders: { 'Accept-Language': localStorage.getItem("selectedLng") } });
        return next.handle(languageRequest).pipe(
          map(event => {
            return event;
          }),
          catchError(error => {
          }),
          finalize(() => {
          })
        )
      }
    }

    Please note that we are reading the selected language from localStorage localStorage.getItem("selectedLng") and passing it in the header of hte HttpRequest object.

    Add the HttpInterceptor into the providers array of your root module like this

    providers: [{ provide: HTTP_INTERCEPTORS, useClass: HTTPListener, multi: true }],

    On the ASP.NET Core side, inside the Configure method of Startup class,

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.Use((context, next) =>
        {
            var userLangs = context.Request.Headers["Accept-Language"].ToString();
            var lang = userLangs.Split(',').FirstOrDefault();
    
            //If no language header was provided, then default to english.
            if(string.IsNullOrEmpty(lang))
            {
                lang = "en";
            }
    
            //You could set the environment culture based on the language.
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    
            //you could save the language preference for later use as well.
            context.Items["SelectedLng"] = lang;
            context.Items["ClientCulture"] = Thread.CurrentThread.CurrentUICulture.Name;
    
    
            return next();
        });
    }

    Thanks.