简体   繁体   中英

c# Web API localization

The title is a little misleading. I have to build a new Web API application to service a bunch of different clients that we are also building. I don't need the parameters or the routes in the API localized.

Basically the clients will ask for a resource in a specified language and the web api will return the results.

My only requirement is that the localization resources will be stored in a SQL DB and not resource files.

Being that the Web API is only returning localized results and it doesn't need to be localized, should I try to be following .NET localization practices or should I just create a simple, cached table lookup function mimicking localization routines?

Technically speaking how you save the localized information at the server side doesn't matter to the client application (calling the API). You can save it in a database or you can save it in resource files; all depends on the architecture of the system.

But you can solve your requirements in two ways:

  1. Put locale in the api url: The client application can supply the appropriate locale as below:

GET https://apiserver.com/api/v1.0.0/en-GB/cities

GET https://apiserver.com/api/v1.0.0/fr-CA/cities

GET https://apiserver.com/api/v1.0.0/en-US/cities

At the server side you can configure your method as below:

[Route("v1.0.0/{locale}/cities")]
[HttpGet]
public List<City> GetCities(string locale)
{
    // Get cities by locale
    return cities;
}
  1. Pass the locale information in HTTP header. At the server side read the locale passed on in the header and send across response accordingly:

     public WebRequest GetWebRequest(Uri uri) { WebRequest request = base.GetWebRequest(uri); request.Headers.Add("locale", "en-GB"); return request; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM