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 –