Domanda

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?

È stato utile?

Soluzione

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());
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top