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

时间:2017-01-28 10:58:23

标签: c# asp.net-core

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

9 个答案:

答案 0 :(得分:34)

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

如果您愿意,请尝试。

用法

程序包管理器控制台

PM> Install-Package AspNetCore.RouteAnalyzer

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

浏览

运行项目,您可以访问网址/routes以查看项目的所有路线信息。

答案 1 :(得分:15)

您可以从IActionDescriptorCollectionProvider获取ActionDescriptor集合。 在那里,您查找项目中提到的所有操作,可以使用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);
    }
}

答案 2 :(得分:5)

使用Swashbuckle为我做了诀窍。

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

答案 3 :(得分:3)

您也可以使用 来自Template = x.AttributeRouteInfo.Template数组的ActionDescriptors.Items值。以下是there的完整代码示例:

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

答案 4 :(得分:2)

如果您不使用MVC致电GetRouteData().Routers.OfType<RouteCollection>().First()来访问RouteCollection

app.UseRouter(r => {
    r.MapGet("getroutes", async context => {
        var routes = context.GetRouteData().Routers.OfType<RouteCollection>().First();
        await context.Response.WriteAsync("Total number of routes: " + routes.Count.ToString() + Environment.NewLine);
        for (int i = 0; i < routes.Count; i++)
        {
            await context.Response.WriteAsync(routes[i].ToString() + Environment.NewLine);
        }               
    });
    // ...
    // other routes
});

确保在路由处理程序中调用GetRouteData(),否则返回null。

答案 5 :(得分:2)

请在我之前为其他答案投票。

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

我也有贡献:

使用匿名类型(避免强对象)(99.9% 的情况下,我更喜欢强类型对象,但这纯粹是一种友好的信息信息)。

空检查安全性(这可能是矫枉过正,但当我试图弄清楚某些事情时,我更喜欢矫枉过正而不是 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);
        }
    }
}
<块引用>

"Name = x.AttributeRouteInfo.Name ?? "n/a",

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

可能需要以下可选包。

 <PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.2.0" />

答案 6 :(得分:1)

您正在尝试获取RouteCollection类型的路由器。要获取该类型的所有路由,您应该能够在.All()类型的路由器上调用RouteCollection

实施例: var routes = RouteData.Routers.OfType<RouteCollection>().All();

信用: https://rimdev.io/get-registered-routes-from-an-asp.net-mvc-core-application/

如果.All()无效,请参阅上文。

答案 7 :(得分:1)

我还使用 IActionDescriptorCollectionProvider RouteValues获取信息。

var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items
    .Select(ad => new
    {
        Action = ad.RouteValues["action"],
        Controller = ad.RouteValues["controller"]
    }).Distinct().ToList();

答案 8 :(得分:1)

使用ActionDescriptor和http方法(获取,发布等)列出路由

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

Result