【问题标题】:MVC4 - Make a value global to whole projectMVC4 - 使整个项目的价值全球化
【发布时间】:2012-08-31 11:05:15
【问题描述】:

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

当然,在客户端,它将存储在 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;
}

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

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案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。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 使用 HttpContext.Current.Response.Cookies["<yourlanguagecookie>"].Value 如果代码是基于 Web 请求执行的,这对所有网站都有效。
    • 是的,基本上我只是在基础设施中创建类来处理它并像我的示例一样获得它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多