有没有办法将所有枚举显示为swagger中的字符串值,而不是int值?
我希望能够提交POST操作,并根据它们的字符串值放置枚举,而不必每次都查看枚举。
我尝试了DescribeAllEnumsAsStrings
,但是服务器收到的是字符串而不是枚举值,这不是我们要找的。
有人解决这个问题了吗?
编辑:
public class Letter
{
[Required]
public string Content {get; set;}
[Required]
[EnumDataType(typeof(Priority))]
public Priority Priority {get; set;}
}
public class LettersController : ApiController
{
[HttpPost]
public IHttpActionResult SendLetter(Letter letter)
{
// Validation not passing when using DescribeEnumsAsStrings
if (!ModelState.IsValid)
return BadRequest("Not valid")
..
}
// In the documentation for this request I want to see the string values of the enum before submitting: Low, Medium, High. Instead of 0, 1, 2
[HttpGet]
public IHttpActionResult GetByPriority (Priority priority)
{
}
}
public enum Priority
{
Low,
Medium,
High
}
发布于 2016-06-06 21:26:11
全局启用
来自the docs
httpConfiguration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "A title for your API");
c.DescribeAllEnumsAsStrings(); // this will do the trick
});
特定属性上的枚举/字符串转换
此外,如果只希望在特定类型和属性上执行此行为,请使用StringEnumConverter:
public class Letter
{
[Required]
public string Content {get; set;}
[Required]
[EnumDataType(typeof(Priority))]
[JsonConverter(typeof(StringEnumConverter))]
public Priority Priority {get; set;}
}
如果您使用的是Newtonsoft和Swashbuckle v5.0.0或更高版本
你还需要这个包:
Swashbuckle.AspNetCore.Newtonsoft
在你的初创阶段:
services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()
这里有一些文档:https://github.com/domaindrivendev/Swashbuckle.AspNetCore#systemtextjson-stj-vs-newtonsoft
发布于 2019-04-06 02:55:01
对于带有Microsoft JSON库(System.Text.Json)的ASP.NET Core3
在Startup.cs/ConfigureServices()中:
services
.AddControllersWithViews(...) // or AddControllers() in a Web API
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
对于带有Json.NET (Newtonsoft.Json)库的ASP.NET核心3
安装Swashbuckle.AspNetCore.Newtonsoft
包。
在Startup.cs/ConfigureServices()中:
services
.AddControllersWithViews(...)
.AddNewtonsoftJson(options =>
options.SerializerSettings.Converters.Add(new StringEnumConverter()));
// order is vital, this *must* be called *after* AddNewtonsoftJson()
services.AddSwaggerGenNewtonsoftSupport();
对于ASP.NET核心2
在Startup.cs/ConfigureServices()中:
services
.AddMvc(...)
.AddJsonOptions(options =>
options.SerializerSettings.Converters.Add(new StringEnumConverter()));
ASP.NET之前的核心版本
httpConfiguration
.EnableSwagger(c =>
{
c.DescribeAllEnumsAsStrings();
});
发布于 2017-03-28 23:42:59
所以我想我也有类似的问题。我正在寻找swagger来生成枚举以及int ->字符串映射。API必须接受int。swagger ui不那么重要,我真正想要的是在另一边使用“真正的”枚举的代码生成(在这种情况下,android应用程序使用改进)。
因此,从我的研究来看,这似乎是Swagger使用的OpenAPI规范的最终限制。不能为枚举指定名称和编号。
我发现最值得关注的问题是https://github.com/OAI/OpenAPI-Specification/issues/681,它看起来“可能很快”,但之后Swagger将不得不更新,在我的情况下Swashbuckle也是如此。
目前,我的变通方法是实现一个文档过滤器,该过滤器查找枚举并用枚举的内容填充相关描述。
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.DocumentFilter<SwaggerAddEnumDescriptions>();
//disable this
//c.DescribeAllEnumsAsStrings()
SwaggerAddEnumDescriptions.cs:
using System;
using System.Web.Http.Description;
using Swashbuckle.Swagger;
using System.Collections.Generic;
public class SwaggerAddEnumDescriptions : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
// add enum descriptions to result models
foreach (KeyValuePair<string, Schema> schemaDictionaryItem in swaggerDoc.definitions)
{
Schema schema = schemaDictionaryItem.Value;
foreach (KeyValuePair<string, Schema> propertyDictionaryItem in schema.properties)
{
Schema property = propertyDictionaryItem.Value;
IList<object> propertyEnums = property.@enum;
if (propertyEnums != null && propertyEnums.Count > 0)
{
property.description += DescribeEnum(propertyEnums);
}
}
}
// add enum descriptions to input parameters
if (swaggerDoc.paths.Count > 0)
{
foreach (PathItem pathItem in swaggerDoc.paths.Values)
{
DescribeEnumParameters(pathItem.parameters);
// head, patch, options, delete left out
List<Operation> possibleParameterisedOperations = new List<Operation> { pathItem.get, pathItem.post, pathItem.put };
possibleParameterisedOperations.FindAll(x => x != null).ForEach(x => DescribeEnumParameters(x.parameters));
}
}
}
private void DescribeEnumParameters(IList<Parameter> parameters)
{
if (parameters != null)
{
foreach (Parameter param in parameters)
{
IList<object> paramEnums = param.@enum;
if (paramEnums != null && paramEnums.Count > 0)
{
param.description += DescribeEnum(paramEnums);
}
}
}
}
private string DescribeEnum(IList<object> enums)
{
List<string> enumDescriptions = new List<string>();
foreach (object enumOption in enums)
{
enumDescriptions.Add(string.Format("{0} = {1}", (int)enumOption, Enum.GetName(enumOption.GetType(), enumOption)));
}
return string.Join(", ", enumDescriptions.ToArray());
}
}
这会在你的swagger-ui上产生类似下面这样的结果,所以至少你可以“看到你在做什么”:
https://stackoverflow.com/questions/36452468
复制相似问题