我的目標是創建支持多種語言的API。避免在API操作上重複代碼,但仍支持多種語言
這是工作,但只有當我打電話
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
上的每個動作,我想能夠避免的。
在WebApiConfig.cs文件我創建了一個路徑,支持多國語言,把該語言的默認路由"{lang}/api/{controller}/{id}"
之前。這意味着對於英語,我可以撥打http://localhost/en/api/service/get
和葡萄牙語http://localhost/pt/api/service/get
。
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApiLocalized",
routeTemplate: "{lang}/api/{controller}/{id}",
constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})"}, // en or en-US
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
在我的行動,我收到的語言,並用它來改變文化。
ServiceController.cs
public class ServiceController : ApiController
{
[HttpGet]
public string Get(string lang)
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
return Resources.Global.Country;
}
}
當我打電話http://localhost/en/api/service/get
或http://localhost/pt/api/service/get
我得到的字符串中各自的語言,完美的工作。
我怎樣才能避免在所有操作使用
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
?
哪裏可以在代碼中寫一次,但仍然得到所需的lang
參數?
- 我已經試過的Global.asax.cs,但我不知道我是否可以(以及如何)獲取
lang
說法。 - 我不知道我是否可以(以及如何)將它放在WebApiConfig.cs。
你想在URL中使用語言而不是查詢參數的任何理由?後者感覺像是一種更清潔的選擇......當然,也可以從請求中的現有標題中獲取。 –
再次看,你的問題似乎不是關於路由的真正問題,而是關於「如何獲得特定語言的資源」。如果你刪除多餘的路由部分將會很有幫助。 –
這將有助於如果你顯示'Resources.Global'類型的順便說一句。我的猜測是它是一個帶有'ResourceManager'屬性的生成類,您可以使用它來獲取具有特定文化的字符串。 –