简体   繁体   中英

List of Api routes of specific controller C#

I have a controller aController

I would like one of the endpoints to return an array of all of the routes that the other endpoint point to.

For example if I have 3 endpoints:

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"]
    }
}

Is there something like this, similar to the getMethods?

Or an easier question. With the name of the method, is there a way for me to get the route?

You can find all of the actions (along with their route data and attribute routes) by injecting the IActionDescriptorCollectionProvider service.See Here .

In asp.net core2.1 Web API,try below codes:

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"]
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM