Swagger UI Web Api documentation Present enums as

2020-02-07 16:01发布

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
}

13条回答
劳资没心,怎么记你
2楼-- · 2020-02-07 16:50

With asp.net core 3

using System.Text.Json.Serialization;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
         services.AddControllers().AddJsonOptions(options =>
             options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

But it seems that Swashbuckle Version 5.0.0-rc4 is not ready to support that. So we need to use an option(deprecated) in the Swashbuckle config file until it supports and reflects it like Newtonsoft library.

public void ConfigureServices(IServiceCollection services)
{ 
      services.AddSwaggerGen(c =>
      {
            c.DescribeAllEnumsAsStrings();

The difference between this answer and other answers is using only the Microsoft JSON library instead of Newtonsoft.

查看更多
登录 后发表回答