views:

34

answers:

2

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 English

Thanks in advance.

A: 

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()); }
Stephen Binns
+1  A: 

You could do the following:

  • In the Match method insert the language ID in the RouteValueDictionary: values["lang"] = theLanguageId;
  • Turn your action's signature into something like ActionResult Index(int lang)
Rune
Great solution! +1
Sig. Tolleranza