Hy,在我的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中 - >索引方法我会在不查询数据库的情况下获取语言ID,因为我已经在LanguageRouteConstraint中完成了。
对不起我的英语不好
提前致谢。
答案 0 :(得分:3)
您可以执行以下操作:
Match
方法中,在RouteValueDictionary
中插入语言ID:values["lang"] = theLanguageId;
ActionResult Index(int lang)
答案 1 :(得分: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()); }