在asp.net mvc 5中保存当前语言(UICulture)的最佳方法是什么?

时间:2015-02-04 21:01:05

标签: asp.net asp.net-mvc session

我想根据请求的网址设置语言。我现在用Session做这件事。但我无法在路线约束中访问会话。问题出现在这里:返回错误,因为' HttpContext.Current.Session '在RouteConstraint中为null。

public class ngnRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
       ...
       Tools.GetCurrentLang();// trying to get language
       ...
    }
}

在工具中:

public static string GetCurrentLang()
{
    if (HttpContext.Current.Session["Lang"] != null)
    {
        return HttpContext.Current.Session["Lang"].ToString();
    }
    else
    {
        return WebConfigurationManager.AppSettings["DefaultLang"];
    }
}  
  

此外,我尝试添加: runAllManagedModulesForAllRequests =" true" 并退出并添加 Seesion 模块,但我收到同样的错误。

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="FormsAuthenticationModule" />
  </modules>
</system.webServer>  

问题: 我能做什么?我可以使用session或cookie处理这个问题吗?你有什么建议?谢谢你的一切。

1 个答案:

答案 0 :(得分:0)

您是否尝试将HttpContextBase参数传递给GetCurrentLang()方法?

public static string GetCurrentLang(HttpContextBase httpContext)
{
    if (httpContext.Session["Lang"] != null)
    {
        return httpContext.Session["Lang"].ToString();
    }
    else
    {
        return WebConfigurationManager.AppSettings["DefaultLang"];
    }
}