简体   繁体   English

如何获取 asp.net 内核中任何 url 的路由值?

[英]How to get route values for any url in asp.net core?

I need to get the route values for an arbitrary URL in ASP.NET MVC Core.我需要在 ASP.NET MVC Core 中获取任意 URL 的路由值。

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.可能是这样的问题: 如何确定任意 URL 是否与定义的路线匹配,因为我还没有找到任何直接的方法来做到这一点。

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!看起来一旦我有一个请求 url 的 HttpContext,就很容易获得路由值,并查看 GitHub 中的aspnet/Hosting的源代码,我到了创建 HttpContextFactory 的地步,但就是这样, go 不能再进一步了!

Does someone know how to do this?有人知道该怎么做吗?

Thanks in advance!提前致谢!

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. 我知道这是一篇较旧的文章,但这是我从基于URL的ASP.NET MVC Core应用程序中运行的RouteCollection中获取RouteData的方法。

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. 根级路由器填充routeContext.RouteData

Ref: Net6 You can install the package and use the namespace using Microsoft.AspNetCore.Routing;参考:Net6 您可以安装 package 并使用using Microsoft.AspNetCore.Routing;

then you can get route values like this然后你可以得到这样的路线值

var routeData = _httpContextAccessor.HttpContext.GetRouteData(); ;
var namedRouteValue = _httpContextAccessor.HttpContext.GetRouteValue("route-key"); 

请尝试;

var t =  ViewContext.RouteData.Values["id"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM