问题描述
改进这个问题,在添加它们之前,如何在 ApplicationModelProvider 中找到 ActionModel 操作的所有现有状态代码?
Improving upon this question, how do I Find All the Existing Status Codes for ActionModel action in ApplicationModelProvider, before adding them?
目前正在调试器中查看action.Filters[0].StatusCode
,但无法在实际代码中访问该属性.在添加之前,需要查看所有 array 列表中 API 控制器操作的状态代码已经存在.
Currently looking through action.Filters[0].StatusCode
in debugger, however cannot access the property in actual code.Need to see what Status codes already exist for API Controller Actions in all array list, before adding it .
将过滤器[0]作为测试
did filters[0] as a test
Net Core API:Make ProducesResponseType 全局参数或自动化
foreach (ControllerModel controller in context.Result.Controllers)
{
foreach (ActionModel action in controller.Actions)
{
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>());
...
}
推荐答案
首先转换为 ProducesResponseTypeAttribute,并获取 StatusCode见下面的代码,
First cast as ProducesResponseTypeAttribute, and get StatusCodeSee code below,
foreach (var filter in action.Filters)
{
if (filter.GetType() == typeof(ProducesResponseTypeAttribute))
{
var producesResponseTypeAttribute = (filter as ProducesResponseTypeAttribute)
var statusCode = producesResponseTypeAttribute.StatusCode;
这篇关于查找控制器 ActionModel 的 API 状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!