开发者

Passing Data by Route Constraint

开发者 https://www.devze.com 2022-12-22 14:56 出处:网络
Hy, in my Global.asax I\'ve this rule: // Home routes.MapRoute(\"Home\", \"{lang}/\", new { lang = \"ita\", controller = \"Home\", action = \"Index\" },

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 the RouteValueDictionary: 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()); }
0

精彩评论

暂无评论...
验证码 换一张
取 消