How can you access RouteData from the code-behind?

asp.netRoutingUrl Routing

asp.net Problem Overview


When using ASP.Net routing, how can you get the RouteData from the code-behind?

I know you can get it from the GetHttpHander method of the RouteHandler (you get handed the RequestContext), but can you get this from the code-behind?

Is there anything like...

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

...that you can access globally, like you can do with HttpContext?

Or is it that RouteData is only meant to be accessed from inside the RouteHandler?

asp.net Solutions


Solution 1 - asp.net

You could also use the following:

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

Solution 2 - asp.net

You can use the following:

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

Solution 3 - asp.net

  [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);
  }

Solution 4 - asp.net

I think you need to create a RouteHandler then you can push the values into HTTPContext during the GetHttpHandler event.

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

You can find more information in this MSDN article.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeaneView Question on Stackoverflow
Solution 1 - asp.netHosam AlyView Answer on Stackoverflow
Solution 2 - asp.netRupert BatesView Answer on Stackoverflow
Solution 3 - asp.netRASKOLNIKOVView Answer on Stackoverflow
Solution 4 - asp.netJeffView Answer on Stackoverflow