How does ContentLanguage.PreferredCulture get set? It's value is changing.
Some explanation in this blog https://beendaved.blogspot.com/2016/05/a-simple-language-selector-in-episerver.html
The blog post does not tell about setting PreferredCulture but tells only how to retrieve it.
Yes it has a sentence explaining it
"Thankfully, there is a PreferredCulture property of the ContentLanguage class that allows us to see what the preferred language - not necessarily the current - is. In my example above with English and Japanese enabled, but only English content existing, choosing Japanese has different results with the code below"
var preferredLang = EPiServer.Globalization.ContentLanguage.PreferredCulture.Name; // Japanese
var currentLang = Model.CurrentPage.Language.Name; // English
This is because the PreferredCulture looks at the following
/// <summary>Gets or sets the preferred content culture.</summary>
/// <value>The current culture.</value>
/// To access the language code which is used to look up information in LocalizationService and/or
/// LanguageBranch, simply read the Name property of the returned CultureInfo object.
public static CultureInfo PreferredCulture
return ContextCache.Current["EPiServer:ContentLanguage"] as CultureInfo ?? ContentLanguage.Instance.SetCulture();
ContextCache.Current["EPiServer:ContentLanguage"] = (object) value;
So it depends what language settings you have set up on your nodes as the preferred language.
What do you mean, when writing that it keeps changing? It changes during the same request context?
In short, this is how it gets set:Before loading the requested content and passing it to your controllers, Episerver will determine the content language by calling this method:
One of the things this method does is determine the content language and set it for the remainder of the HttpContext. That is, unless some custom code changes the value.
Besides, touching the content language, it also determines the culture and UI culture of the current thread.
"How does ContentLanguage.PreferredCulture get set? It's value is changing."
It uses the LanguageResolver, which ultimately tries pulling the CultureInfo from System.Globalization, unless the culture for the current request is explicitly set, as in a language setting for the site navigated or the URL you are on or via host. The fallback language comes in to play if the culture info cannot be retrieved or determined. It shouldn't change on you unexpectedly. You would see changes if you are toggling your language setting, URL with lang specified, or playing with the Epi UI language, as I believe being logged in to Epi will cause the LanguageResolver to use your UI language unless, again, the URL specifies something different.
Now, the details of how it resolves the culture is a bit of a rabit hole to trace down, so I can't provide a nice code clip of it like above. However, the above clip that shows the "ContentLanguage.Instance.SetCulture()" is where it begins.