获取ASP.NET Core中的所有已注册路由

Bea*_*ind 33 c# asp.net-core

我是.NET Core的新手.我想获得ASP.NET Core中所有已注册路由的列表.在ASP.NET MVC中我们有路由表System.Web.Routing,在ASP.NET Core中是否有相同的东西?我想在Controller Action中获取路由列表.

kob*_*ake 49

我创建了NuGet包"AspNetCore.RouteAnalyzer",它提供了获取所有路径信息的功能.

如果你愿意,试试吧.

用法

包管理器控制台

PM> Install-Package AspNetCore.RouteAnalyzer
Run Code Online (Sandbox Code Playgroud)

Startup.cs

using AspNetCore.RouteAnalyzer; // Add
.....
public void ConfigureServices(IServiceCollection services)
{
    ....
    services.AddRouteAnalyzer(); // Add
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ....
    app.UseMvc(routes =>
    {
        routes.MapRouteAnalyzer("/routes"); // Add
        ....
    });
}
Run Code Online (Sandbox Code Playgroud)

浏览

运行项目,您可以访问该URL /routes以查看项目的所有路径信息.

  • NuGet 包不再维护,并且无法与 core 2.2 及更高版本一起使用。下面的答案要简单得多,并且适用于 MVC 和 razor 页面。 (18认同)
  • 这次真是万分感谢.出色的工作! (5认同)

Edg*_*ita 18

您可以从中获取ActionDescriptor集合IActionDescriptorCollectionProvider.在那里,您查找项目中引用的所有操作,并且可以获取AttributeRouteInfoRouteValues包含有关de路由的所有信息.

例:

public class EnvironmentController : Controller
{
    private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;

    public EnvironmentController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
    {
        _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
    }

    [HttpGet("routes", Name = "ApiEnvironmentGetAllRoutes")]
    [Produces(typeof(ListResult<RouteModel>))]
    public IActionResult GetAllRoutes()
    {

        var result = new ListResult<RouteModel>();
        var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Where(
            ad => ad.AttributeRouteInfo != null).Select(ad => new RouteModel
            {
                Name = ad.AttributeRouteInfo.Name,
                Template = ad.AttributeRouteInfo.Template
            }).ToList();
        if (routes != null && routes.Any())
        {
            result.Items = routes;
            result.Success = true;
        }
        return Ok(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为应该有一个更简单的方法...... :(到目前为止,所有这些asp.net核心MVC的东西看起来都很复杂.不知道为什么他们没有提供从传统MVC轻松过渡... (5认同)
  • 根据您的回答,我更新了操作以返回包含所有路由和相应控制器/操作的 HTML 响应:https://pastebin.com/WK7GPrQf (3认同)

neu*_*t47 18

您还可以使用 数组中的Template = x.AttributeRouteInfo.TemplateActionDescriptors.Items。这是那里的完整代码示例:

    [Route("monitor")]
    public class MonitorController : Controller {
        private readonly IActionDescriptorCollectionProvider _provider;

        public MonitorController(IActionDescriptorCollectionProvider provider) {
          _provider = provider;
        }

        [HttpGet("routes")]
        public IActionResult GetRoutes() {
            var routes = _provider.ActionDescriptors.Items.Select(x => new { 
               Action = x.RouteValues["Action"], 
               Controller = x.RouteValues["Controller"], 
               Name = x.AttributeRouteInfo.Name, 
               Template = x.AttributeRouteInfo.Template 
            }).ToList();
            return Ok(routes);
        }
      }
Run Code Online (Sandbox Code Playgroud)


Gui*_*ume 6

使用Swashbuckle对我有用

您只需要在要列出的控制器(及其动作)上使用AttributeRouting


Ref*_*eft 5

使用 ActionDescriptor WITH http 方法(get、post 等)列出路由

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Infrastructure;

[Route("")]
[ApiController]
public class RootController : ControllerBase
{
    private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;

    public RootController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
    {
        _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
    }

    public RootResultModel Get()
    {
        var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Where(
            ad => ad.AttributeRouteInfo != null).Select(ad => new RouteModel
        {
            Name = ad.AttributeRouteInfo.Template,
            Method = ad.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods.First(),
            }).ToList();

        var res = new RootResultModel
        {
            Routes = routes
        };

        return res;
    }
}

internal class RouteModel
{
    public string Name { get; set; }
    public string Template { get; set; }
    public string Method { get; set; }
}

internal class RootResultModel
{
    public List<RouteModel> Routes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

结果


gra*_*der 5

请在我的答案之前对其他答案进行投票。

我的贡献是将几个答案合并为一个。

我还贡献了:

使用匿名类型(以避免强对象)(99.9%的时间,我更喜欢强类型对象,但这纯粹是友好的信息信息)。

null 检查安全性(这可能有点矫枉过正,但当我试图找出答案时,我更喜欢矫枉过正而不是 ArgumentNullException)。

我添加了“使用”语句。#喘气

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace My.WebApiProject.Controllers
{
    public class EnvironmentController : Controller
    {
        private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;

        public EnvironmentController(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
        {
            _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
        }

        [HttpGet("routes", Name = "ApiEnvironmentGetAllRoutes")]
        public IActionResult GetAllRoutes()
        {
            /* intentional use of var/anonymous class since this method is purely informational */
            var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items
                .Where(ad => ad.AttributeRouteInfo != null)
                .Select(x => new {
                Action = null != x && null != x.RouteValues && null != x.RouteValues["action"] ? x.RouteValues["action"] : "n/a",
                Controller = null != x && null != x.RouteValues && null != x.RouteValues["controller"] ? x.RouteValues["controller"] : "n/a",
                Name = x.AttributeRouteInfo.Name ?? "n/a",
                Template = x.AttributeRouteInfo.Template ?? "n/a",
                Method = x.ActionConstraints?.OfType<HttpMethodActionConstraint>().FirstOrDefault()?.HttpMethods.First()
                }).ToList();
            return Ok(routes);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

“名称 = x.AttributeRouteInfo.Name ??“不适用”,

“n/a”实际上有时会出现。

可能需要以下可选包。

 <PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />
Run Code Online (Sandbox Code Playgroud)


小智 5

可以通过从 DI 检索 EndpointDataSource 的集合来列出路由的集合。

.NET 6 的示例:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();

if (app.Environment.IsDevelopment())
{
    app.MapGet("/debug/routes", (IEnumerable<EndpointDataSource> endpointSources) =>
        string.Join("\n", endpointSources.SelectMany(source => source.Endpoints)));
}

app.Run();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

欲了解更多详情,请访问此处