Reputation: 9356
I want to output a list of HTTP methods that users can use for a particular route name.
E.g.
[HttpGet("somethingcool",Name="name"]
public IActionResult Get(){ Ok(); }
[HttpPost("somethingcool",Name="name"]
public IActionResult Post(){ Ok(); }
When I try to get the HTTP methods that route name
can accept, I want to see GET, POST
Any ideas?
Upvotes: 1
Views: 1880
Reputation: 4517
MS provide a NuGet package to reflect on your code and find the methods your api supports. See more here: MSDN | Creating Help Pages for ASP.NET Web API
Then in you controller you can get the information from
Configuration.Services.GetApiExplorer().ApiDescriptions
I assume you want to expose the list of methods to clients. For this you should use OPTIONS verb which is made for exactly this purpose: MDN | OPTIONS
Upvotes: 1
Reputation: 56859
In concept what you are asking to do isn't possible. This is because a single route can refer to any number of action methods. Naming a route is also optional. Routes are primarily designed to match the current request, so getting a list of all of the routes that match any possible request is not something that is built-in to routing.
But if you are using attribute routing exclusively, you could use Reflection to scan for HttpGet
and HttpPost
attributes in controller classes and then filter the list of attributes by the Name property.
var classes = assembly.GetTypes().Where(t => t.GetTypeInfo().IsClass && t.Name.EndsWith("Controller"));
foreach (var c in classes)
{
var methods = c.GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (var method in methods)
{
var getAtt = method.GetCustomAttribute(typeof(HttpGetAttribute));
var postAtt = method.GetCustomAttribute(typeof(HttpPostAttribute));
// Check whether they are null and add metadata to your result list
}
}
If you are using convention-based routing, you would need to mark methods that refer to convention-based routes with a custom attribute to indicate which route it corresponds to.
[RouteName("default")]
Then scan for that attribute similarly to how you would for HttpGet
and HttpPost
. But you would have to be diligent to ensure every route actually has a name and every method has one of the possible attributes to search for in order for it to work.
Upvotes: 0