Asp.net mvc 按路由约束传递数据
Hy,在我的Global.asax中,我有一条规则:Asp.net mvc 按路由约束传递数据,asp.net-mvc,constraints,Asp.net Mvc,Constraints,Hy,在我的Global.asax中,我有一条规则: // Home routes.MapRoute("Home", "{lang}/", new { lang = "ita", controller = "Home", action = "Index" }, new { lang = new LanguageRouteConstraint() }
// 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中完成了此操作
我很抱歉我的英语不好
提前感谢。您可以根据语言限制通过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()); }
您可以执行以下操作:
- 在
方法中,在Match
中插入语言ID:RouteValueDictionary
values[“lang”]=languageID代码>
- 将动作的签名转换为类似于
ActionResult索引(int-lang)