I am trying to find Http verb (Get, Post, Push, Delete, etc) of every Controller API Method action. Background: trying to create ProducesResponseType Status code documentation for Swagger, by reviewing http action (company has business rules linking action to required ProducesResponseType StatusCode).
So how to locate HTTP action verb of a Controller?
This seems to be coming close in debugging, however, this does not seem right.
foreach (ControllerModel controller in context.Result.Controllers)
{
foreach (ActionModel action in controller.Actions)
controller.Actions.[0].ActionMethod.CustomAttributes[2]
Referring Code:
Net Core API: Make ProducesResponseType Global Parameter or Automate
ProduceResponseTypeModelProvider.cs
public class ProduceResponseTypeModelProvider : IApplicationModelProvider
{
public int Order => 3;
public void OnProvidersExecuted(ApplicationModelProviderContext context)
{
}
public void OnProvidersExecuting(ApplicationModelProviderContext context)
{
foreach (ControllerModel controller in context.Result.Controllers)
{
foreach (ActionModel action in controller.Actions)
{
// I assume that all you actions type are Task<ActionResult<ReturnType>>
Type returnType = action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments()[0];
action.Filters.Add(new ProducesResponseTypeAttribute(StatusCodes.Status510NotExtended));
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status200OK));
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status500InternalServerError));
}
}
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, ProduceResponseTypeModelProvider>());
...
}
Is there simpler method to detect action verb of a Controller Method?
Questions below are for previous .Net. We have .Net Core 2.2.
How do I get http verb attribute of an action using refection - ASP.NET Web API
Detect if action is a POST or GET method
These were answers in regular .Net
Answers before:
var methodInfo = MethodBase.GetCurrentMethod();
var attribute = methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true).Cast<ActionMethodSelectorAttribute>().FirstOrDefault();
if (HttpContext.Request.HttpMethod == HttpMethod.Post.Method)
{
// The action is a post
}