对于我的应用程序,我想将 url 与所有注册的路由进行匹配,以查看是否存在匹配项。
当有匹配时,我想从匹配中提取路由值。
我在 ASP.NET Core 2.1 中得到了这个工作,但我似乎无法按照在 .NET Core 3 中检索路由的方式检索路由
工作 ASP.NET Core 2.1 示例:
string url = "https://localhost/Area/Controller/Action";
// Try to match against the default route (but can be any other route)
Route defaultRoute = this._httpContextAccessor.HttpContext.GetRouteData().Routers.OfType<Route>().FirstOrDefault(p => p.Name == "Default");
RouteTemplate defaultTemplate = defaultRoute.ParsedTemplate;
var defaultMatcher = new TemplateMatcher(defaultTemplate, defaultRoute.Defaults);
var defaultRouteValues = new RouteValueDictionary();
string defaultLocalPath = new Uri(url).LocalPath;
if (!defaultMatcher.TryMatch(defaultLocalPath, defaultRouteValues))
{
return null;
}
string area = defaultRouteValues["area"]?.ToString();
string controller = defaultRouteValues["controller"]?.ToString();
string actiondefaultRouteValues["action"]?.ToString();
Run Code Online (Sandbox Code Playgroud)
有没有办法获取所有注册的端点(模板)并与这些模板进行匹配?
在 ASP.NET Core 2.1 及更低版本中,路由是通过实现IRouter将传入 URL 映射到处理程序的接口来处理的。您通常不会直接实现接口,而是依赖MvcMiddleware添加到中间件管道末尾的实现。
在 ASP.NET Core 3.0 中,我们使用端点路由,因此路由步骤与端点的调用是分开的。实际上,这意味着我们有两个中间件:
EndpointRoutingMiddleware它执行实际的路由,即计算将为给定的请求 URL 路径调用哪个端点。
EndpointMiddleware调用端点。
因此,您可以尝试以下方法将 url 与所有注册的路由进行匹配,以查看 asp.net core 3.0 中是否存在匹配项。
public class TestController : Controller
{
private readonly EndpointDataSource _endpointDataSource;
public TestController ( EndpointDataSource endpointDataSource)
{
_endpointDataSource = endpointDataSource;
}
public IActionResult Index()
{
string url = "https://localhost/User/Account/Logout";
// Return a collection of Microsoft.AspNetCore.Http.Endpoint instances.
var routeEndpoints = _endpointDataSource?.Endpoints.Cast<RouteEndpoint>();
var routeValues = new RouteValueDictionary();
string LocalPath = new Uri(url).LocalPath;
//To get the matchedEndpoint of the provide url
var matchedEndpoint = routeEndpoints.Where(e => new TemplateMatcher(
TemplateParser.Parse(e.RoutePattern.RawText),
new RouteValueDictionary())
.TryMatch(LocalPath, routeValues))
.OrderBy(c => c.Order)
.FirstOrDefault();
if (matchedEndpoint != null)
{
string area = routeValues["area"]?.ToString();
string controller = routeValues["controller"]?.ToString();
string action = routeValues["action"]?.ToString();
}
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以参考此博客了解有关 ASP.NET Core 3.0 中端点路由的更多详细信息。
| 归档时间: |
|
| 查看次数: |
2745 次 |
| 最近记录: |