1

sModel:

public class Product
{
    public string NameEN { get; set; }
    public string NameFR { get; set; }
    public double Price { get; set; }
}

Controller :

    // GET: api/Products/5
    [ResponseType(typeof(Product))]
    public IHttpActionResult GetProduct(int id)
    {
        return Ok(new Product(){NameEN = "Cookie", NameFR = "Biscuit", Price = 10});
    }

I want this result :

{"Name" = "Cookie", "Price" = "10"}

The produtcs are store in a database

How can I transform my properties NameEN and NameFR to Name during the serialization with the desired Accept-Language?

Thank you

jonlabr
  • 417
  • 1
  • 7
  • 9

1 Answers1

2

You can create and access culture specific strings using a resource file.

First create a resource file and name it according to the culture code. So for the default you'll have Names.resx and for french you'll have Names.fr-FR.resx. From here you should open up the properties of each resx file and give it a similar custom tool namespace such as ViewRes. Now when you access the resx file to grab a string like so: ViewRes.Names.MyString you'll get the string according to the current culture defined in Thread.CurrentThread.CurrentCulture which you can set. You can set this using the accept-language in your Global.asax.cs file like so:

protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    string culture = HttpContext.Request.ServerVariables.Get("HTTP_ACCEPT_LANGUAGE");
    CultureInfo ci = culture as CultureInfo;
    if (ci == null)
        ci = new CultureInfo("en");
    Thread.CurrentThread.CurrentUICulture = ci;
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}

Now the next time you access ViewRes.Names in your controller it will be with the culture set by accept-language.

You can also set the culture when accessing your resx strings like so:

[ResponseType(typeof(Product))]
public IHttpActionResult GetProduct(int id, string culture)
{
    ViewRes.Names.Culture = new CultureInfo(culture);
    return Ok(new Product(){Name = ViewRes.Names.MyString, Price = 10});
}
James Santiago
  • 2,883
  • 4
  • 22
  • 29
  • It can not work because the products are store in a database. Example of product : 1. Cookie, Biscuit, 1.99$ 2. Car, Automobile, 4999$ My product are dynamic. I can't use resx for storing my value. – jonlabr Feb 20 '15 at 02:44
  • @jonlabr you'll need to apply you own logic then. Capture and parse the accept-language value and present the name value accordingly. See https://stackoverflow.com/questions/9927871/need-an-example-on-how-to-get-preferred-language-from-accept-language-request-he – James Santiago Feb 20 '15 at 04:18
  • I can't believe this feature is not include :( Thank you! – jonlabr Feb 20 '15 at 12:19