2010-03-12 204 views
1

海蘭傳遞數據,在我的Global.asax我有這樣的規則:通過路由約束

// Home 
    routes.MapRoute("Home", 
        "{lang}/", 
        new { lang = "ita", controller = "Home", action = "Index" }, 
        new { lang = new LanguageRouteConstraint() } 
       ); 

而且我LanguageRouteConstraint類:

public class LanguageRouteConstraint : IRouteConstraint 
    { 
    #region Membri di IRouteConstraint 

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     if ((routeDirection == RouteDirection.IncomingRequest) && (parameterName.ToLower(CultureInfo.InvariantCulture) == "lang")) 
     { 
     try 
     { 
      string lang = Convert.ToString(values[parameterName]); 

      // Language check on db 
      Language currLang = new Language().Get(lang); 
      if (currLang != null) 
      { 
      // Here I'd like to "save (in session|querystring|....)" the id 
      return true; 
      } 
     } 
     catch 
     { 
      return false; 
     } 
     } 
     return false; 
    } 

    #endregion 
    } 

我的控制器

public class HomeController : Controller 
{ 
    public ActionResult Index(string lang) 
    { 
    // I would get the language ID without interrogating the data base 
    } 
} 

在HomeController - > Index方法中,我會在不詢問數據庫的情況下獲得語言ID,因爲我已經在LanguageRouteC onstraint。

對不起,我可憐的英語

在此先感謝。

回答

3

你可以做到以下幾點:

  • Match方法中,在RouteValueDictionary中插入語言ID:values["lang"] = theLanguageId;
  • 把你的行動的簽名改成類似ActionResult Index(int lang)
+0

的最佳解決方案! +1 – 2010-03-16 15:21:04

0

你可以在你的語言約束通過HttpContext的訪問當前會話

Language currLang = new Language().Get(lang); 
    if (currLang != null) 
    { 
    httpContext.Session["Lang"] = id 
    return true; 
    } 

然後在你的控制器,你可以使用屬性

public int Language { get return int.Parse(Session["Lang"].ToString()); }