2

I need to get the route values for an arbitrary URL in ASP.NET MVC Core.

It could be something like this SO question: How to determine if an arbitrary URL matches a defined route, because I haven't found any direct way to do it.

And I haven't been able to do it with that approach either.

It looks like once I have an HttpContext with a Request for the url, it's easy to get the route values, and looking at the source code for aspnet/Hosting in GitHub I got to the point where HttpContextFactory gets created, but that was it, just couldn't go any further!

Does someone know how to do this?

Thanks in advance!

Hinek
  • 9,215
  • 12
  • 51
  • 71
Miguel Veloso
  • 1,047
  • 10
  • 16
  • Could you share with us what you tried. It's hard to guess what you're trying to solve. – Jasen Jul 11 '17 at 23:22
  • You should probably also check out the aspnet/Routing repository :) – juunas Jul 12 '17 at 06:07
  • I'm trying to get the RouteValues out of the referrer url from the Request object, to implement a simple view navigation scheme. It's as if I createed a new Request object with the referrer url and get the RouteValues out of it. – Miguel Veloso Jul 17 '17 at 17:25

2 Answers2

0

I know this an older post, but this is what I did in order to get RouteData from a RouteCollection running in an ASP.NET MVC Core app based on a URL.

public async Task<ActionResult> GetRouteDataForUrl([FromQuery(Name = "url")] string url)
{
  var uri = new Uri(url);

  var httpContext = new DefaultHttpContext();
  httpContext.Request.Path = uri.PathAndQuery;

  var routeContext = new RouteContext(httpContext);
  var router = RouteData.Routers.First(); //get the top level router

  await router.RouteAsync(routeContext); //router updates routeContext

  return new JsonResult(routeContext.RouteData.Values);
}

The routeContext.RouteData is populated by the root level router.

-2

Try please;

var t =  ViewContext.RouteData.Values["id"];
bobbyrne01
  • 5,926
  • 14
  • 70
  • 139
A.Kosecik
  • 43
  • 3