Is there a way to display all enums as their string value in swagger instead of their int value?
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.
I tried DescribeAllEnumsAsStrings
but the server then receives strings instead of the enum value which is not what we're looking for.
Has anyone solved this?
Edit:
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
}
if anyone is interested i have modified the code to work with
.NET CORE 3 and Swagger V5
I just did this and it works fine!
Startup.cs
Model.cs
swagger.json
I hope this helps you how it helped me!
write code inside Startup.cs
ASP.NET Core 3.1
To generate enums as strings using Newtonsoft JSON you must explicitly add Newtonsoft support by adding
AddSwaggerGenNewtonsoftSupport()
as follows:This is available via a new package,
Swashbuckle.AspNetCore.Newtonsoft
. It looks like everything else works fine without this package apart from enum converter support..Net Core 3.0
From the docs:
Also, if you want this behavior only on a particular type and property, use the StringEnumConverter: