本文介绍了Swagger UI Web Api文档将枚举形式表示为字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以将所有枚举以字符串形式而不是以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:
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;}
}
这篇关于Swagger UI Web Api文档将枚举形式表示为字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!