Net Core API:使 ProducesResponseType 全局参数或自动化 [英] Net Core API: Make ProducesResponseType Global Parameter or Automate

查看:38
本文介绍了Net Core API:使 ProducesResponseType 全局参数或自动化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有 100 多个 API,并且必须为顶部的所有 API、200、500 等编写 ProducesResponseType.重复代码?努力让API遵循Dry原则,成为瘦控制器.

We have 100+ APIs and have to write ProducesResponseType for all our APIS at the top, 200, 500, etc. Is there a method to make this global parameter for all our get functions, so we don't have to continue repeating code? Trying to make APIs follow Dry principle and be thin controllers.

[HttpGet("[Action]/{id}")]
[ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<GetBookResponse>> GetByBook(int id)
{
   var book = await bookservice.GetBookById(id);
   return Ok(book);
}

资源:

为多个HttpStatusCodes设置一个ProducesResponseType typeof

Net Core API:ProducesResponseType 的目的

推荐答案

您可以创建自定义 IApplicationModelProvider 并在 OnProvidersExecuting 方法中添加您需要的过滤器.

You can create a custom IApplicationModelProvider and add the filters you need in OnProvidersExecuting method.

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));
            }
        }
    }
}

然后需要注册到IServiceCollection

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...   
    services.TryAddEnumerable(ServiceDescriptor.Transient<IApplicationModelProvider, ProduceResponseTypeModelProvider>());
    ...
}

这篇关于Net Core API:使 ProducesResponseType 全局参数或自动化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆