【发布时间】:2019-09-25 03:20:12
【问题描述】:
我正在尝试查找每个控制器 API 方法操作的 Http 动词(获取、发布、推送、删除等)。背景:尝试通过查看 http 操作(公司有将操作链接到所需的 ProducesResponseType StatusCode 的业务规则)为 Swagger 创建 ProducesResponseType 状态代码文档。
那么如何定位一个Controller的HTTP动作动词呢?
这似乎在调试中接近了,但是,这似乎不对。
foreach (ControllerModel controller in context.Result.Controllers)
{
foreach (ActionModel action in controller.Actions)
controller.Actions.[0].ActionMethod.CustomAttributes[2]
推荐代码:
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>());
...
}
是否有更简单的方法来检测控制器方法的动作动词?
以下问题适用于以前的 .Net。我们有 .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
这些是常规 .Net 中的答案
之前的答案:
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
}
【问题讨论】:
标签: c# .net asp.net-core .net-core asp.net-core-mvc