Get all registered routes in ASP.NET Core

前端 未结 8 1376
独厮守ぢ
独厮守ぢ 2020-12-02 12:07

I am new to .NET Core. I want to get a list of all registered routes in ASP.NET Core. In ASP.NET MVC we had route table in System.Web.Routing, is there somethin

相关标签:
8条回答
  • 2020-12-02 13:04

    You can take an ActionDescriptor collection from IActionDescriptorCollectionProvider. In there, you can see all actions referred to in the project and can take an AttributeRouteInfo or RouteValues, which contain all information about the routes.

    Example:

        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);
            }
        }
    
    0 讨论(0)
  • 2020-12-02 13:05

    Using Swashbuckle did the trick for me.

    You just need to use AttributeRouting on controllers you want to list (and on their actions)

    0 讨论(0)
提交回复
热议问题