问题
I want to use OutputCache to open pages quickly.
I wrote in controller:
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 );
}
}
In 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>
In 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 );
}
But I cannot change site language. For example, I switch language to English, It changes, but then want to return Azerbaijan language, it did not changes. What is my mistake? (Sorry for bad English)
回答1:
I solved myself, changed
<globalization culture="en" uiCulture="en" />
to
<globalization culture="auto" uiCulture="auto" />
in config file. Then it worked.
来源:https://stackoverflow.com/questions/12653343/outputcache-not-let-to-change-site-language