2017-01-14 31 views
3

最近,我創建了一個新的ASP.NET核心Web應用程序,我的要求之一是爲客戶端公開終端以獲取存儲在.resx文件中的所有翻譯密鑰和值。如何獲取ResourceManager中的所有密鑰

在ASP.NET Core之前,我能夠做到這一點。但該命令ResourceManager.GetResourceSet()不再被認可:

public IActionResult Get(string lang) 
{ 
    var resourceObject = new JObject(); 

    var resourceSet = Resources.Strings.ResourceManager.GetResourceSet(new CultureInfo(lang), true, true); 
    IDictionaryEnumerator enumerator = resourceSet.GetEnumerator(); 
    while (enumerator.MoveNext()) 
    { 
     resourceObject.Add(enumerator.Key.ToString(), enumerator.Value.ToString()); 
    } 

    return Ok(resourceObject); 
} 

有什麼新的方法來獲取資源的所有鍵和值在ASP.NET核心項目?

回答

6

如果你看看documentation,你會看到ASP.NET Core Team已經推出了IStringLocalizerIStringLocalizer<T>。在封面下,IStringLocalizer使用ResourceManagerResourceReader。從文檔基本用法:

using Microsoft.AspNetCore.Mvc; 
using Microsoft.Extensions.Localization; 

namespace Localization.StarterWeb.Controllers 
{ 
    [Route("api/[controller]")] 
    public class AboutController : Controller 
    { 
     private readonly IStringLocalizer<AboutController> _localizer; 

     public AboutController(IStringLocalizer<AboutController> localizer) 
     { 
      _localizer = localizer; 
     } 

     [HttpGet] 
     public string Get() 
     { 
      return _localizer["About Title"]; 
     } 
    } 
} 

爲了讓所有的鍵,你可以這樣做:

var resourceSet = _localizer.GetAllStrings().Select(x => x.Name); 

但對於通過語言讓所有按鍵,你需要使用WithCulture方法:

var resourceSet = _localizer.WithCulture(new CultureInfo(lang)) 
          .GetAllStrings().Select(x => x.Name); 

因此,當您將IStringLocalizer注入您的控制器時,它將被實例化爲ResourceManagerStringLocalizer類的實例,默認爲CultureInfo,用於您的ap並且爲了獲取特定於您的lang變量的資源,您需要使用WithCulture方法,因爲它會爲特定的CultureInfo創建新的ResourceManagerStringLocalizer類。

+0

這正是我所需要的。非常感謝。 – Sobhan

相關問題