2015-02-04 50 views
1

我想根據請求的url設置語言。現在我正在使用Session進行此操作。但我無法訪問路由約束中的會話。問題發生在這裏:返回錯誤,因爲'HttpContext.Current.Session'在RouteConstraint中爲null。在asp.net mvc中保存當前語言(UICulture)的最佳方式是什麼5

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 = 「真」和移去那些所謂並添加SEESION模塊,但我得到了同樣的錯誤。

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

問題: 我能做什麼呢?我可以通過會話或cookie處理這個問題嗎?你有什麼建議?謝謝你的一切。

回答

0

你是否嘗試過將HttpContextBase參數傳遞給你的GetCurrentLang()方法?

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

不,但'HttpContextBase httpContext'的** httpContext.Session **在Match函數中爲null。問題是:我認爲會話尚未初始化。 –

相關問題