如何使用Swashbuckle和.net core记录身体参数

问题描述

我们正在使用Swashbuckle.AspNetCore版本=“ 5.6.3”为.Net core 3.1 Web服务生成swagger(v2)文档。 在.Net core中,有两种指定主体参数的方法

1. public void someActionMethod (Guid id,[FromBody] item){...}
2. public void SomeActionMethod (Guid id) {
              var item = Request.Body;
   }

我们正在使用API​​Controller为主体参数使用第二个选项。在这种情况下,swashbuckle无法推断所需的body参数,因此文档中将其丢失。 任何人都可以指出是否有一种无需使用[FromBody]即可指定和生成body参数文档的方法吗? 它是现有的API,因此我想避免仅出于文档目的而更改签名。

解决方法

请找到dotnet core 3.1 @ https://github.com/domaindrivendev/Swashbuckle.AspNetCore的解决方案 如果您配置newtonsoft json格式化程序,则api项目应安装Swashbuckle.AspNetCore.Newtonsoft

 public void ConfigureServices(IServiceCollection services)
    {
         services.AddControllers().AddNewtonsoftJson(); //Configure Newtonsoft json formatter

            services.AddSwaggerGen(c =>
        {
             c.SwaggerDoc("test",new OpenApiInfo { Title = "test  API Service",Version = "v2.0.1"});

            c.AddSecurityDefinition("oauth2",new OpenApiSecurityScheme
            {
                Description = "Access Token Authentication. Example: \"bearer {token}\"",In = ParameterLocation.Header,Name = "Authorization",Type = SecuritySchemeType.ApiKey
            });
       
            c.OperationFilter<SecurityRequirementsOperationFilter>();                             
        });

        services.AddSwaggerGenNewtonsoftSupport(); //Add swagger support for newtonsoft json formatter
    }
    
     public void Configure(IApplicationBuilder app,IWebHostEnvironment e)
    {   
           app.UseSwagger();
      
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/test/swagger.json","Test  API v1");
           // c.DefaultModelsExpandDepth(-1);
           // c.DocExpansion(DocExpansion.None);
           // c.EnableFilter();
           // c.EnableDeepLinking();                
        });
    }