来自唯一JSON资源的ASP.NET Core本地化 [英] ASP.NET Core localization from unique JSON resource

查看:137
本文介绍了来自唯一JSON资源的ASP.NET Core本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有多个视图(包括部分共享视图)和需要本地化的控制器的ASP.NET Core(.NETCoreApp 1.1)Web应用程序.

约束是本地化字符串位于具有以下结构的单个JSON文件中(只要保留在一个文件中就可以更改):

{
  "HELLO": {
    "en": "Hello!",
    "fr": "Bonjour !"
  }
}

所以我想我需要的是访问此唯一文件的本地化,并提供可以在控制器和视图中使用的IStringLocalizerIViewLocalizer对象,例如_localizer["HELLO"],显然这不是默认模式. /p>

要为此增加麻烦,我还需要能够默认情况下自动从浏览器自动检测首选语言,或显式地将一种语言作为路由值,例如/en/Home/Index或/fr/Home/索引,还有/Home/Index.

我对ASP.NET Core还是非常陌生的,即使有了文档和各种示例来实现位或我需要的东西,我也无法实现可在生产中使用的任何可靠的东西.我遇到的所有内容要么丢失,要么过时.

如果能理解这些内容的人能告诉我该怎么做,我将不胜感激!

我想我已经弄清楚了如何从路线或从浏览器中获取语言,如果路线中没有任何内容.这是我所做的:

我的路由模板是template: "{lang?}/{controller=Home}/{action=Index}/{id?}"),这是我用来从控制器获取lang的代码:

string lang = this.RouteData.Values["lang"] as string;
if (lang == null)
{
    string userLangs = HttpContext.Request.Headers["Accept-Language"].ToString();
    lang = userLangs.Split(',').FirstOrDefault();
}

解决方案

关于使用Json文件,我采用了这段代码此处,然后将其修改为使用单个文件.在LocalizerUtil类中,我只返回ExpandPathIterator"Resources \ Localisation";它非常粗糙,但是这意味着我可以为每种语言使用一个json文件.它不会在一个文件中执行嵌套语言,但我相信您可以进一步对其进行修改.

我们采用了将语言选择存储在cookie中并允许用户通过下拉菜单交换语言的方法.

Startup.cs

// Add localization
services.AddJsonLocalization(opts => { opts.ResourcesPath = "Resources"; });

// Add framework services.
services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization();

services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("en"),
                new CultureInfo("fr"),
            };

            options.DefaultRequestCulture = new RequestCulture("en");
            // Formatting numbers, dates, etc.
            options.SupportedCultures = supportedCultures;
            // UI strings that we have localized.
            options.SupportedUICultures = supportedCultures;
        });

然后结合使用博客文章中,语言切换器正常工作.如果您想使用url方案,那么博客文章也会对此进行介绍.

I am working on an ASP.NET Core (.NETCoreApp 1.1) web application with several views (including partial shared ones) and controllers that requires localization.

The constraint is that the localization strings are inside a single JSON file that has the following structure (can be changed as long as it remains in one single file):

{
  "HELLO": {
    "en": "Hello!",
    "fr": "Bonjour !"
  }
}

So I guess what I need is the localization to access this unique file and provide IStringLocalizer and IViewLocalizer objects that I can use in my controllers and views like _localizer["HELLO"], obviously it is not the default pattern.

To add difficulty to this, I also need to be able to automatically detect the preferred language from the browser by default or explicitly take a language as a route value, for instance /en/Home/Index or /fr/Home/Index but also /Home/Index.

I am very new to ASP.NET Core and even with the documentation and various example achieving bits or what I need I haven't been able to implement anything reliable that I can use in production. Everything I came across has either something missing or is somehow outdated.

I would be grateful if someone who understand those things could show me how to do this!

Edit: I think I have figured out how to get the language from the route or from the browser if nothing in route. Here is what I did:

My route template is template: "{lang?}/{controller=Home}/{action=Index}/{id?}") and here is the code I use to get the lang from a controller:

string lang = this.RouteData.Values["lang"] as string;
if (lang == null)
{
    string userLangs = HttpContext.Request.Headers["Accept-Language"].ToString();
    lang = userLangs.Split(',').FirstOrDefault();
}

解决方案

With regards to using a Json file, I took this code here and then modified it to use a single file. In the LocalizerUtil class, the ExpandPathIterator I just return "Resources\Localisation"; Its very crude but it means that I can have a single json file for each language. It doesn't do the nested languages within one file but I'm sure you could further modify it to do that too.

We went the route of storing the language choice in a cookie and allowing the user to swap languages with a dropdown.

Startup.cs

// Add localization
services.AddJsonLocalization(opts => { opts.ResourcesPath = "Resources"; });

// Add framework services.
services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization();

services.Configure<RequestLocalizationOptions>(options =>
        {
            var supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("en"),
                new CultureInfo("fr"),
            };

            options.DefaultRequestCulture = new RequestCulture("en");
            // Formatting numbers, dates, etc.
            options.SupportedCultures = supportedCultures;
            // UI strings that we have localized.
            options.SupportedUICultures = supportedCultures;
        });

And then using a combination of this and this blog post to get the language switcher working. If you want to use a url scheme the blog posts touch on that too.

这篇关于来自唯一JSON资源的ASP.NET Core本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆