Passing Data by Route Constraint
Hy, in my Global.asax I've this rule:
// Home
routes.MapRoute("Home",
"{lang}/",
new { lang = "ita", controller = "Home", action = "Index" },
new { lang = new LanguageRouteConstraint() }
);
And my LanguageRouteConstraint class:
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
}
And my controller
public class HomeController : Controller
{
public ActionResult Index(string lang)
{
// I would get the language ID without interrogating the data base
}
}
In HomeController-->Index method I would get the language ID without interrogating the data base because I have already done in LanguageRouteConstraint.
I'm sorry for my poor Englis开发者_如何学Goh
Thanks in advance.
You could do the following:
- In the
Match
method insert the language ID in theRouteValueDictionary
:values["lang"] = theLanguageId;
- Turn your action's signature into something like
ActionResult Index(int lang)
You can access the current session via httpContext on your language constraint
Language currLang = new Language().Get(lang);
if (currLang != null)
{
httpContext.Session["Lang"] = id
return true;
}
then in your controller you could use a property
public int Language { get return int.Parse(Session["Lang"].ToString()); }
精彩评论