문제

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