如何从代码隐藏中访问RouteData?

时间:2009-06-10 16:52:09

标签: asp.net routing url-routing

使用ASP.Net路由时,如何从代码隐藏中获取RouteData?

我知道你可以从RouteHandler的GetHttpHander方法获得它(你得到了RequestContext),但是你可以从代码隐藏中得到它吗?

有什么类似......

RequestContext.Current.RouteData.Values["whatever"];

...您可以全局访问,就像使用HttpContext一样?

或者是否只能从RouteHandler内部访问RouteData?

4 个答案:

答案 0 :(得分:158)

您还可以使用以下内容:

//using System.Web;
HttpContext.Current.Request.RequestContext.RouteData

答案 1 :(得分:33)

您可以使用以下内容:

RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));

答案 2 :(得分:0)

我认为你需要创建一个RouteHandler然后你可以在GetHttpHandler事件期间将值推送到HTTPContext。

foreach (var urlParm in requestContext.RouteData.Values) {
    requestContext.HttpContext.Items[urlParm.Key] = urlParm.Value;
}

您可以在this MSDN article中找到更多信息。

答案 3 :(得分:0)

  [HttpGet]
  [Route("{countryname}/getcode/")]
  public string CountryPhonecode()
  {
     // Get routdata by key, in our case it is countryname
     var countryName = Request.GetRouteData().Values["countryname"].ToString();

     // your method
     return GetCountryCodeByName(string countryName);
  }
相关问题