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?

有帮助吗?

解决方案

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());
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top