.Net Core Localization Integration

Hello all,

Newby here.
I was trying to find an example where I can integrate multi-language through:
Microsoft.AspNetCore.Mvc.Localization
So I can use for example .Title instead of creating if statement for .Title.de or .Title.en.
The same way you do it with AppResource.
Is there an easy way to implement proper localization integration?
Best,
F.

There are several options.

In step 1 you have to setup ASP.NET Localization. Then you will have the current language code globally available as CultureInfo.CurrentUICulture.ToString().

Then you have different options:

1. Decide about language in Client

When you have localizable fields you bind them to Dictionaries. https://docs.squidex.io/02-documentation/software-development-kits/.net-standard#1-create-your-class-model

I would create a custom dictionary like so:

public sealed class LocalizedValue<T> : Dictionary<string, T>
{
  public T Value
  {
    get
    {
      var language = CultureInfo.CurrentUICulture.ToString();

      // Get value current request language.
      if (this.TryGetValue(language, out var value))
      {
          return value;
      }

      // Get value by master language.
      if (this.TryGetValue("master", out value))
      {
          return value;
      }

      return default;
    }
  }
}

You can also implement ToString() and an implicit conversion operator.

Then you define your model like this:

public sealed class BlogPostData
{
    // For localizable fields you can use dictionaries.
    public LocalizedValue<string> Title { get; set; }
}

public sealed class BlogPost : Content<BlogPostData>
{
}

The advantage is that if you want to cache requests, you only have to cache them once.

2. Decide about language in Client

You have to pass the language to Squidex via the X-Languages and X-Flatten header.

You have several options again:

In each request

Read more about it here: https://docs.squidex.io/02-documentation/concepts/localization#how-to-retrieve-the-correct-languages

var language = CultureInfo.CurrentUICulture.ToString();

var context =
  QueryContext.Default
    .WithFlatten()
    .WithLanguages(language);

var content = await contents.GetAsync(id, contex);

Then you can configure your mode llike this:

public sealed class BlogPostData
{
    // This is in the global request.
    public string Title { get; set; }
}

public sealed class BlogPost : Content<BlogPostData>
{
}

In all requests

If you want to add headers for all requests you can do that. It follows the principles described here:

The options object has a new property called ClientFactory now. This is an example implementation.

You can also write such a factory that adds the language headers to each request based on the current culture.

1 Like

Thanks a lot.
I will try it out…Appreciate your support.
Curious to know how you will implement for all requests.

See above, I have updated my answer.