1

I have the need to set the current language according to specific rules. I need to have access to the current page and the current user to make decisions on. I've looked through the documentation and it said to use the InitializeCulture method on PageBase. My project is using MVC not WebForms, what is the equivalent of InitializeCulture in MVC?

Andreas
  • 1,355
  • 9
  • 15

1 Answers1

4

You can implement an IAuthorizationFilter and do your checks in OnAuthorization. It is possible to do it in an IActionFilter as well, but OnAuthorization is called earlier. You will have access to the current HttpContext and from there you can get the current page data.

public class LanguageSelectionFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        // access to HttpContext
        var httpContext = filterContext.HttpContext;

        // the request's current page
        var currentPage = filterContext.RequestContext.GetRoutedData<PageData>();

        // TODO: decide which language to use and set them like below
        ContentLanguage.Instance.SetCulture("en");
        UserInterfaceLanguage.Instance.SetCulture("en");
    }
}

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        // register the filter in your FilterConfig file.
        filters.Add(new LanguageSelectionFilter());
    }
}
aolde
  • 2,287
  • 16
  • 19
  • 1
    Thank you! This looks like what I was after. We managed to get away with the normal fallback behaviours in EPiServer and my question was due to a bug in EPiServer. If I was on a page in french and had a call to swedish page in my view like the following @Url.PageUrl(page.LinkURL). It turns out the "LinkURL" actually contained "epslanguage=fr" even though the page was the swedish one. I solved it by using my own HtmlHelper for Urls: https://gist.github.com/anonymous/8565072 – Andreas Jan 22 '14 at 18:56