1
我想使用OutputCache快速打开页面。OutputCache不允许更改站点语言
我在控制器中写道:
public class HomeController : Controller
{
[OutputCache(Duration=3600,VaryByParam="none", VaryByCustom="lang")]
public ActionResult Index()
{
//........
}
public ActionResult ChangeCulture(string lang, string returnUrl)
{
Session["Culture"] = new CultureInfo(lang);
return Redirect(returnUrl);
}
}
在Layout.cshtml:
<a href="@Url.Action("ChangeCulture", "Home", new { lang = "en", returnUrl = this.Request.RawUrl })">Eng</a>
<a href="@Url.Action("ChangeCulture", "Home", new { lang = "az", returnUrl = this.Request.RawUrl })">Az</a>
在Global.asax中:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//It's important to check whether session object is ready
if (HttpContext.Current.Session != null)
{
CultureInfo ci = (CultureInfo)this.Session["Culture"];
//Checking first if there is no value in session and set default language this can happen for first user's request
if (ci == null)
{
//Sets default culture to english invariant
string langName = "az";
//Try to get values from Accept lang HTTP header
if (HttpContext.Current.Request.UserLanguages != null &&
HttpContext.Current.Request.UserLanguages.Length != 0)
{
//Gets accepted list
langName = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);
}
ci = new CultureInfo(langName);
this.Session["Culture"] = ci;
}
//Finally setting culture for each request
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
}
public override string GetVaryByCustomString(HttpContext context, string value)
{
if (value.ToLower() == "lang")
{
return Thread.CurrentThread.CurrentUICulture.Name;
}
return base.GetVaryByCustomString(context, value);
}
但我不能改变网站的语言。例如,我将语言切换到英语,它发生变化,但后来想要返回阿塞拜疆语,它没有改变。我的错误是什么? (对不起,我英文不好)
你如何区分语言?参数?例如(/ en-us/controller/action)或其他方式?基本上你需要使用OutputCache的VaryBy(?)属性来缓存不同的语言 – Tommy
我在家庭控制器中使用这个动作: public ActionResult ChangeCulture(string lang,string returnUrl) Session [“Culture”] = new CultureInfo(lang); return Redirect(returnUrl); } 和 保护无效Application_AcquireRequestState(对象发件人,EventArgs的) {} Global.asax中方法。 请分享有关使用VaryBy(?)属性的示例链接。我想让OutputCache不保存语言资源。 –
我找到了一个链接 http://adamyan.blogspot.com/2010/02/aspnet-mvc-2-localization-complete.html –