Swagger UI Web Api 文档 将枚举显示为字符串? [英] Swagger UI Web Api documentation Present enums as strings?
问题描述
有没有办法将所有枚举显示为它们的字符串值,而不是它们的 int 值?
Is there a way to display all enums as their string value in swagger instead of their int value?
我希望能够提交 POST 操作并根据其字符串值放置枚举,而不必每次都查看枚举.
I want to be able to submit POST actions and put enums according to their string value without having to look at the enum every time.
我尝试了 DescribeAllEnumsAsStrings
但服务器然后接收字符串而不是我们正在寻找的枚举值.
I tried DescribeAllEnumsAsStrings
but the server then receives strings instead of the enum value which is not what we're looking for.
有人解决了吗?
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
}
推荐答案
全局启用
来自文档:
httpConfiguration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "A title for your API");
c.DescribeAllEnumsAsStrings(); // this will do the trick
});
特定属性的枚举/字符串转换
此外,如果您只希望对特定类型和属性进行此行为,请使用 StringEnumConverter:
Enum/string conversion on particular property
Also, if you want this behavior only on a particular type and property, use the 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 或更高版本
你还需要这个包:
If you're using Newtonsoft and Swashbuckle v5.0.0 or higher
You'll also need this package:
Swashbuckle.AspNetCore.Newtonsoft
这在您的启动中:
services.AddSwaggerGenNewtonsoftSupport(); // explicit opt-in - needs to be placed after AddSwaggerGen()
这里有文档:https://github.com/domaindrivendev/Swashbuckle.AspNetCore#systemtextjson-stj-vs-newtonsoft
这篇关于Swagger UI Web Api 文档 将枚举显示为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!