【发布时间】:2018-04-20 05:59:29
【问题描述】:
我使用“消息”中的查询参数,这些参数可以超过100个并且是可选的。签名应保持这种形式。
所以我的问题是,我怎样才能记录一些查询参数,以显示在 swagger UI 中,并保持可尝试性?
/// <summary>
/// Callback Endpoint
/// </summary>
/// <returns>HTTP 200 <see cref="HttpStatusCode.OK"/>.</returns>
/// <param name="message">The message</param>
[HttpGet]
[SwaggerParameter("Something", "It is something")]
[Route("endpoint", Name = nameof(Endpoint))]
public virtual async Task<HttpResponseMessage> Endpoint(HttpRequestMessage message)
要忽略“HttpRequestMessage”,我使用 OperationFilter: ASP.Net Web API Swashbuckle how to ignore HttpRequestMessage
config.EnableSwagger(swagger =>
{
swagger.OperationFilter<IgnoreHttpRequestMessage>();
swagger.OperationFilter<SwaggerParameterAttributeHandler>();
[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 Description { get; private set; }
public bool Required { get; set; } = false;
}
public class SwaggerParameterAttributeHandler : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
// Get all SwaggerParameterAttributes on the method
var attributes = apiDescription.ActionDescriptor.GetCustomAttributes<SwaggerParameterAttribute>(true);
if (operation.parameters == null)
{
operation.parameters = new List<Parameter>();
}
foreach (var attribute in attributes)
{
var parameter = operation.parameters.FirstOrDefault(p => p.name == attribute.Name);
if (parameter != null)
{
parameter.required = attribute.Required;
}
else
{
operation.parameters.Add(new Parameter()
{
name = attribute.Name,
description = attribute.Description,
type = "string",
required = attribute.Required
});
}
}
}
}
【问题讨论】:
-
上面的代码会发生什么?在
Apply方法中创建参数时,您可能需要指定位置,即@in = "query"用于查询字符串参数。
标签: c# .net swagger swashbuckle