Swagger参数的默认值

z0qdvdin  于 2023-08-05  发布在  其他
关注(0)|答案(5)|浏览(285)

如何定义以下API生成的swagger中属性的默认值?

public class SearchQuery
{
        public string OrderBy { get; set; }

        [DefaultValue(OrderDirection.Descending)]
        public OrderDirection OrderDirection { get; set; } = OrderDirection.Descending;
}

public IActionResult SearchPendingCases(SearchQuery queryInput);

字符串
Swashbuckle生成OrderDirection作为所需参数。我希望它是可选的,并向客户端指示默认值(不确定swagger是否支持)。
我不喜欢使属性类型为空。还有别的选择吗?理想情况下使用内置类...
我使用Swashbuckle。AspNetCore -https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio

jhiyze9q

jhiyze9q1#

我总是这样设置参数本身的默认值:

public class TestPostController : ApiController
{
    public decimal Get(decimal x = 989898989898989898, decimal y = 1)
    {
        return x * y;
    }
}

字符串
下面是在swagger-ui上的样子:
http://swashbuckletest.azurewebsites.net/swagger/ui/index#/TestPost/TestPost_Get

更新

在讨论了注解之后,我更新了Swagger-Net,以通过反射读取DefaultValueAttribute

public class MyTest
{
    [MaxLength(250)]
    [DefaultValue("HelloWorld")]
    public string Name { get; set; }
    public bool IsPassing { get; set; }
}


下面是swagger json的样子:

"MyTest": {
  "type": "object",
  "properties": {
    "Name": {
      "default": "HelloWorld",
      "maxLength": 250,
      "type": "string"
    },
    "IsPassing": {
      "type": "boolean"
    }
  },
  "xml": {
    "name": "MyTest"
  }
},


Swagger-Net的源代码如下:
https://github.com/heldersepu/Swagger-Net
测试项目的源代码在这里:
https://github.com/heldersepu/SwashbuckleTest

r6hnlfcb

r6hnlfcb2#

如果可以在控制器中设置默认参数值,那么它的工作方式是这样的

// GET api/products
[HttpGet]
public IEnumerable<Product> Get(int count = 50)
{
    Conn mySqlGet = new Conn(_connstring);
    return mySqlGet.ProductList(count);
}

字符串

31moq8wy

31moq8wy3#

这适用于ASP.net MVC5,代码对.Net Core无效
1-按如下方式定义自定义属性

public class SwaggerDefaultValueAttribute: Attribute
{
   public SwaggerDefaultValueAttribute(string param, string value)
   {
      Parameter = param;
      Value = value;
   }
   public string Parameter {get; set;}
   public string Value {get; set;}
}

字符串
2-定义Swagger OperationFilter类

public class AddDefaulValue: IOperationFilter
{
   void IOperationFilter.Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
   {
      if (operation.parameters == null || !operation.parameters.Any())
      {
         return;
      }
      var attributes = apiDescription.GetControllerAndActionAttributes<SwaggerDefaultValueAttribute>().ToList();

      if (!attributes.Any())
      {
         return;
      }
      
      foreach(var parameter in operation.parameters)
      {
         var attr = attributes.FirstOrDefault(it => it.Parameter == parameter.name);
         if(attr != null)
         {
            parameter.@default = attr.Value;
         }
      }
   } 
}


3-在SwaggerConfig文件中注册OperationFilter

c.OperationFilter<AddDefaultValue>();


4-用属性装饰控制器方法

[SwaggerDefaultValue("param1", "AnyValue")]
public HttpResponseMessage DoSomething(string param1)
{
   return Request.CreateResponse(HttpStatusCode.OK);
}

wsewodh2

wsewodh24#

第一种方法

根据其中一个答案here,您应该能够简单地将以下内容添加到您的模型中,尽管我还没有验证这一点:

public class ExternalJobCreateViewModel
{
    ///<example>Bob</example>
    public string CustomFilename { get; set; }
    ...etc

字符串

第二种方式

在.net 6中,我使用了以下代码:

public class MyFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {

        if (operation.OperationId.Equals("somecontroller_somepath", StringComparison.OrdinalIgnoreCase))
        {                
            operation.Parameters.Clear();
            operation.Parameters = new List<OpenApiParameter>
            {
                new OpenApiParameter()
                {
                    Name = "document-name",
                    Schema = new OpenApiSchema()
                    {
                        Type = "string",
                    },
                    Example = new Microsoft.OpenApi.Any.OpenApiString("docName1"),
                    In = ParameterLocation.Query
                },
                new OpenApiParameter()
                {
                    Name = "user-email",
                    Schema = new OpenApiSchema()
                    {
                        Type = "string",
                    },
                    Example = new Microsoft.OpenApi.Any.OpenApiString("elvis.presley@somemail.com"),
                    In = ParameterLocation.Query
                },
                new OpenApiParameter()
                {
                    Name = "account-type-id",
                    Schema = new OpenApiSchema()
                    {
                        Type = "string",
                    },
                    Example = new Microsoft.OpenApi.Any.OpenApiString("2"),
                    In = ParameterLocation.Query
                }
            };
        }
    }
}


然后在Program.cs中

builder.Services.AddSwaggerGen(options =>
            {
                ... other stuf
                options.OperationFilter<MyFilter>();

第三种方法

  • 我从未用过这段代码,所以没有测试 *

在.net 6和Piggybacking关闭Sameh的答案.
要使用多个属性,请像这样装饰属性类:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class SwaggerDefaultValueAttribute : Attribute
{
 ... etc


对于swashbuckle的6.5.0,我认为属性是这样的:

public class AddDefaulValueFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null || !operation.Parameters.Any())
        {
            return;
        }
        context.ApiDescription.TryGetMethodInfo(out var x);
        if (x != null)
        {
            return;
        }
        var attributes = x!.GetCustomAttributes<SwaggerDefaultValueAttribute>().ToList();

        if (!attributes.Any())
        {
            return;
        }

        foreach (var parameter in operation.Parameters)
        {
            var attr = attributes.FirstOrDefault(it => it.Parameter == parameter.Name);
            if (attr != null)
            {
                parameter.Schema.Default = new OpenApiString(attr.Value);
            }
        }
    }
}


由于我试图在多部分消息上使用此消息作为主体参数,因此我必须这样做,但使用风险自担:

public class AddDefaulValueFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if(operation.RequestBody == null)
        {
            return;
        }
        var keys = operation.RequestBody.Content.Where(val => val.Key == "multipart/form-data").Take(1).ToList();
        if(!keys.Any())
        {
            return;
        }
        var props = keys.FirstOrDefault().Value.Schema.Properties;
        if (props == null || !props.Any())
        {
            return;
        }
        context.ApiDescription.TryGetMethodInfo(out var x);
        if (x == null)
        {
            return;
        }
        var attributes = x!.GetCustomAttributes<SwaggerDefaultValueAttribute>().ToList();

        if (!attributes.Any())
        {
            return;
        }

        foreach (var prop in props)
        {
            var attr = attributes.FirstOrDefault(it => it.Parameter == prop.Key);
            if (attr != null)
            {
                prop.Value.Default = new OpenApiString(attr.Value);
            }
        }
    }
}

o8x7eapl

o8x7eapl5#

在YAML文件中,可以定义需要哪些属性。此示例来自NSwag配置。

/SearchPendingCases:
    post:
      summary: Search pending cases
      description: Searches for pending cases and orders them
      parameters:
        - in: body
          name: SearchQuery 
          required: true
          schema:
            type: object
            required:
              - OrderBy
              # do not include OrderDirection here because it is optional
            properties:
              OrderBy:
                description: Name of property for ordering
                type: string
                # you can remove the following two lines 
                # if you do not want to check the string length
                minLength: 1    
                maxLength: 100
              OrderDirection:
                description: Optional order direction, default value: Descending
                type: string
                enum: [Ascending, Descending] # valid enum values
                default: Descending           # default value

字符串
Swagger - Enums
Swagger - Unlocking the Spec: The default keyword

相关问题