15

我在我的 Web API 中使用 Swashbuckle(C# 的招摇)。我有几个返回列表的 GET 端点,我允许用户将每页和页面参数添加到 QueryString

示例:http ://myapi.com/endpoint/?page=5&perpage=10

我看到 swagger 确实支持“查询”中的参数,但我如何让 Swashbuckle 做到这一点?


我在其中一条评论中提到,我通过创建自定义属性来解决我的问题,以允许我做我需要的事情。以下是我的解决方案的代码:

[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class SwaggerParameterAttribute : Attribute
{
    public SwaggerParameterAttribute(string name, string description)
    {
        Name = name;
        Description = description;
    }

    public string Name { get; private set; }
    public Type DataType { get; set; }
    public string ParameterType { get; set; }
    public string Description { get; private set; }
    public bool Required { get; set; } = false;
}

使用 Swagger Config 注册属性:

GlobalConfiguration.Configuration 
    .EnableSwagger(c =>
        {
            c.OperationFilter<SwaggerParametersAttributeHandler>();
        });

然后将此属性添加到您的方法中:

[SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
[SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)]
4

3 回答 3

10

你可以很容易地做到这一点。假设你有一个ItemsController这样的动作:

[Route("/api/items/{id}")]
public IHttpActionResult Get(int id, int? page = null, int? perpage = null)
{
   // some relevant code
   return Ok();
}

Swashbuckle 将生成此规范(仅显示相关部分):

"paths":{  
  "/api/items/{id}":{  
     "get":{  
        "parameters":[  
           {  
              "name":"id",
              "in":"path",
              "required":true,
              "type":"integer",
              "format":"int32"
           },
           {  
              "name":"page",
              "in":"query",
              "required":false,
              "type":"integer",
              "format":"int32"
           },
           {  
              "name":"limit",
              "in":"query",
              "required":false,
              "type":"integer",
              "format":"int32"
           }
        ]
     }
  }

当您想要page并且perpage被要求时,只需使参数不可为空。

于 2016-03-08T21:12:00.783 回答
6

以下是 Attribute 方法所需步骤的摘要(ASP.Net Core 2.1、Swashbuckle.AspNetCore v4.0.1)。我需要一个以“$”开头的参数,所以可选参数不是一个选项!

SwaggerParameterAttribute.cs

     [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
     public class SwaggerParameterAttribute : Attribute
     {
         public SwaggerParameterAttribute(string name, string description)
        {
            Name = name;
            Description = description;
        }

        public string Name { get; private set; }
        public string DataType { get; set; }
        public string ParameterType { get; set; }
        public string Description { get; private set; }
        public bool Required { get; set; } = false;
    }

SwaggerParameterAttributeFilter.cs

using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq;
public class SwaggerParameterAttributeFilter : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        var attributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
            .Union(context.MethodInfo.GetCustomAttributes(true))
            .OfType<SwaggerParameterAttribute>();

        foreach (var attribute in attributes)
            operation.Parameters.Add(new NonBodyParameter
            {
                Name = attribute.Name,
                Description = attribute.Description,
                In = attribute.ParameterType,
                Required = attribute.Required,
                Type = attribute.DataType
            });              
    }
}

在 Startup.ConfigureServices 添加这个

 using Swashbuckle.AspNetCore.Swagger;
 services.AddSwaggerGen(c =>
 {
      c.OperationFilter<SwaggerParameterAttributeFilter>();
      c.SwaggerDoc("v1.0", new Info { Title = "My API", Version = "v1.0" });
 });

并像这样使用:

[SwaggerParameter("$top", "Odata Top parameter", DataType = "integer", ParameterType ="query")]

数据类型可以是:整数、字符串、布尔值

ParameterTypes:可以是路径、正文、查询

于 2018-11-15T15:38:48.203 回答
0

这里有一些关于 SwaggerParametersAttributeHandler 缺失信息的评论。它是一个操作过滤器,可帮助您确定对属性执行的操作。

这是我使用的示例处理程序,它允许我使用 SwaggerParameterAttribute 覆盖可为空参数的必填字段。

public class RequiredParameterOverrideOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        // Get all SwaggerParameterAttributes on the method
        var attributes = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerParameterAttribute>();

        if (operation.parameters == null)
        {
            operation.parameters = new List<Parameter>();
        }

        // For each attribute found, find the operation parameter (this is where Swagger looks to generate the Swagger doc)
        // Override the required fields based on the attribute's required field
        foreach (var attribute in attributes)
        {
            var referencingOperationParameter = operation.parameters.FirstOrDefault(p => p.name == attribute.Name);

            if (referencingOperationParameter != null)
            {
                referencingOperationParameter.required = attribute.Required;
            }
        }
    }
}
于 2017-12-08T16:28:34.753 回答