特定控制器C#的Api路由列表

时间:2018-08-30 15:25:15

标签: c# api asp.net-core

我有一个控制器public class AController : Controller { [HttpGet("BRoute")] public string B(){ return "1"} [HttpGet("CRoute")] public string C(){ return "2"} [HttpGet("DRoute")] public string D(){ return "3"} [HttpGet("GetAllRoutes")] public string GetAllRoutes(){ var allRoutes = typeof(AController).GetRoutes() //Does not exist return allRoutes //Return ["BRoute", "CRoute", "DRoute", "GetAllRoutes"] } }

我希望其中一个端点返回另一个端点指向的所有路由的数组。

例如,如果我有3个端点:

trait Parent

case class ChildA(field1: Int) extends Parent

case class ChildB(field1: Int, field2: Int) extends Parent

是否有类似getMethods的东西?

或更简单的问题。使用方法的名称,我有办法得到路线吗?

1 个答案:

答案 0 :(得分:0)

通过注入IActionDescriptorCollectionProvider服务,您可以找到所有操作(以及它们的路由数据和属性路由)。请参见Here

在asp.net core2.1 Web API中,尝试以下代码:

public class ValuesController : Controller
{
    private readonly IActionDescriptorCollectionProvider _provider;

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

    [HttpGet("BRoute")]
    public string B() { return "1"; }

    [HttpGet("CRoute")]
    public string C() { return "2"; }

    [HttpGet("DRoute")]
    public string D() { return "3"; }

    [HttpGet("GetAllRoutes")]
    public IActionResult GetRoutes()
    {          
        ArrayList allRoutes = new ArrayList();
        foreach (var item in _provider.ActionDescriptors.Items)
        {
            var Template = item.AttributeRouteInfo.Template;
            Template = Template.Substring(Template.LastIndexOf("/") + 1);
            allRoutes.Add(Template);
        }

        return Ok(allRoutes);//Return ["BRoute", "CRoute", "DRoute", "GetAllRoutes"]
    }

}