我有几个使用资源文件的.aspx页面,如下所示:
string TheLanguage = "fr"; //or "de", or "en" ... can be different for each request
CultureInfo newCulture = new CultureInfo(TheLanguage);
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = newCulture;
Page.Culture = TheLanguage;
string SomePageText = GetGlobalResourceObject("SomePage", "SomeResource").ToString();
如您所见,TheLanguage
可以在运行时更改。如果我在此页面上实现输出缓存,页面是否会使用页面在其生命周期中运行时确定的语言进行缓存,然后当新请求进入其他语言时,输出将是上一次运行的输出或缓存会考虑不同的语言吗?
答案 0 :(得分:2)
你是如何实现输出缓存的?是这样的.aspx文件是这样的吗?
<%@ OutputCache Duration="99999" VaryByParam="*" blabala....
如果是这样,你可以使用VaryByCustom属性区分不同的语言,如此
<%@ OutputCache Duration="99999" VaryByParam="*" VaryByCustom="language" blabala....
并将以下代码添加到Global.asax
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg == "language")
{
return Thread.CurrentThread.CurrentCulture.Name;
}
return string.Empty;
}
答案 1 :(得分:2)
根据您的输入,我可以设置工作页面:
我假设你已经有一个像这样映射的友好路线;如果没有,那么你可以根据自己的需要添加它:
routes.MapPageRoute("", "{locale}", "~/default.aspx");
然后在Page_Load
default.aspx.cs
中,我获得了语言并分配了这样的线程文化:
protected void Page_Load(object sender, EventArgs e)
{
// "locale" is the query parameter that we defined in the route config.
// default the language to English if none is specified in the URL.
// E.g. www.mysite.com will default to English instead of throwing an exception.
var language = Page.RouteData.Values["locale"] as string ?? "en";
// set the language, culture etc.
var newCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = newCulture;
Page.Culture = language;
// do other stuff
}
在default.aspx
中,添加OutputCache
指令(注意它是如何引用相同的参数名称“locale”):
<%@ OutputCache Duration="60" VaryByCustom="locale" VaryByParam="None" %>
身体:
<div class="row">
<div class="col-md-4">
<h2>Language</h2>
<p>
<%= Page.Culture %>
</p>
</div>
<div class="col-md-4">
<h2>Last Updated</h2>
<p>
<%= DateTime.Now.ToString() %>
</p>
</div>
</div>
我们现在需要做的就是在GetVaryByCustomString
下的Application_Start
覆盖Global.asax.cs
:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
// let the base method handle everything else
if (!custom.Equals("locale", StringComparison.CurrentCultureIgnoreCase))
return base.GetVaryByCustomString(context, custom);
// if the query param is "locale", return a string that varies with the value.
// in our case, since we're setting `CurrentUICulture`, we can use its `Name`.
return Thread.CurrentThread.CurrentUICulture.Name;
}
运行此命令会根据使用的语言将页面缓存60秒: