2016-12-22 36 views
4

我已經爲我的視圖設置了文化,並在控制器中更改了文化,但我似乎無法找到如何知道我目前使用的文化控制器,我正在尋找類似:在控制器中獲取當前文化asp.net-core

public class HomeController : Controller { 
    public async Task<IActionResult> Index() 
    { 
     // Something like the next line 
     var requestCulture = GetRequestedCulture() 
     return View(); 
    } 
} 

感謝您的幫助

+1

你如何設置(保存)選定的文化?在cookie中,或者您正在鏈接應用程序域的UICulture? –

+0

在餅乾:)謝謝! – JohnnyAce

+0

它回答你的問題嗎? –

回答

6

答案是在請求對象,下面的代碼:

public async Task<IActionResult> Index() { 
    // Retrieves the requested culture 
    var rqf = Request.HttpContext.Features.Get<IRequestCultureFeature>(); 
    // Culture contains the information of the requested culture 
    var culture = rqf.RequestCulture.Culture; 
    return View(); 
} 
0

JohnnysAce答案的作品。如果你只是想要一個簡單的方法來獲取當前的文化,它是在.NET一如既往做到:

CultureInfo uiCultureInfo = Thread.CurrentThread.CurrentUICulture; 
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; 

如果你想使用IRequestCultureFeature(見JohnnyAces回答;因爲依賴注入和更好的可測性的) ,你必須在Startup.cs中配置一些東西。微軟在這裏提供了一個樣本https://github.com/aspnet/Entropy/blob/dev/samples/Localization.StarterWeb/Startup.cs

相關問題