0

我正在使用具有多语言支持的数据库。现在的问题是我需要在查询中输入我的语言才能获取信息,这很好,但是存储该信息的最佳方式是什么。

当然,在客户端,它将存储在 cookie 中。现在我能想到的唯一方法是在类上创建全局变量,然后在我的函数中使用它。这是唯一的方法吗?

示例代码

private string lang = Infrastructure.UserSettings.Language(); // I don't have this implemented yet

[HttpGet]
public dynamic List()
{
    string lang = "English"; // That's why I set it here manually for testing

    var items = _db.Items.OrderByDescending(x => x.ID).Select(x => new
    {
        ID = x.ID,
        Price = x.Price,
        Name = x.ItemTranslations.Where(y => y.Language.Name == lang).Select(y => y.Name).SingleOrDefault(),
        Category =  new {
            ID = x.Category.ID,
            Name = x.Category.CategoryTranslations.Where(y => y.Language.Name == lang).Select(y => y.Name).SingleOrDefault()
        }
    });

    return items;
}

我的问题:这是这样做的好方法还是有一些更优化的方法?

4

2 回答 2

1

您可以使用只读变量制作基本控制器,如下所示:

public class BaseController : Controller
{
    public string UserLanguage
    {
        get
        {
            var cLanguage = HttpContext.Request.Cookies["lang"];
            if (cLanguage != null)
                return cLanguage.Value;
            else
                return "English";
        }
    }
}

然后继承您的基本控制器,如下所示:

public class HomeController : BaseController

然后像这样访问您的变量:

var items = _db.Items.OrderByDescending(x => x.ID).Select(x => new
{
    ID = x.ID,
    Price = x.Price,
    Name = x.ItemTranslations.Where(y => y.Language.Name == UserLanguage).Select(y => y.Name).SingleOrDefault(),
    Category =  new {
        ID = x.Category.ID,
        Name = x.Category.CategoryTranslations.Where(y => y.Language.Name == lang).Select(y => y.Name).SingleOrDefault()
    }
});

您只需要在特定时间设置 cookie。

于 2012-09-06T18:07:19.060 回答
0

每个页面请求都会向服务器发送一个 cookie。如果设置在 cookie 中可用,只需在需要查询时读取 cookie。读取已经存在的 cookie 没有性能开销。

于 2012-09-06T15:37:21.467 回答