【问题标题】:Web Api - Localization Property valueWeb Api - 本地化属性值
【发布时间】:2015-02-19 21:33:43
【问题描述】:

s型号:

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

控制器:

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

我想要这个结果:

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

产品存储在数据库中

如何在序列化过程中使用所需的 Accept-Language 将我的属性 NameEN 和 NameFR 转换为 Name?

谢谢

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api json.net


    【解决方案1】:

    您可以使用资源文件创建和访问特定于文化的字符串。

    首先创建一个资源文件,根据文化代码命名。因此,默认情况下您将拥有Names.resx,而对于法语,您将拥有Names.fr-FR.resx。从这里您应该打开每个 resx 文件的属性并为其提供类似的自定义工具命名空间,例如 ViewRes。现在,当您访问 resx 文件以获取如下字符串时:ViewRes.Names.MyString 您将根据您可以设置的Thread.CurrentThread.CurrentCulture 中定义的当前文化获得字符串。您可以使用 Global.asax.cs 文件中的接受语言进行设置,如下所示:

    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);
    }
    

    现在下次您在控制器中访问ViewRes.Names 时,它将使用accept-language 设置的文化。

    您还可以在访问 resx 字符串时设置文化,如下所示:

    [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});
    }
    

    【讨论】:

    • 它无法工作,因为产品存储在数据库中。产品示例: 1. Cookie, Biscuit, 1.99$ 2. Car, Automobile, 4999$ 我的产品是动态的。我不能使用 resx 来存储我的值。
    • @jonlabr 然后你需要应用你自己的逻辑。捕获并解析接受语言值并相应地呈现名称值。见stackoverflow.com/questions/9927871/…
    • 我不敢相信这个功能不包括在内:(谢谢!
    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2014-04-04
    • 1970-01-01
    相关资源
    最近更新 更多