Michael Pedersen
Michael Pedersen

Reputation: 91

Swagger / Swashbuckle string property options

We have an API in our .Net Core 3.1 project that has a controller which returns a model that is documented by Swagger (Generated by Swashbuckle). The consumer of the endpoint would like to see the options that a given property may return. For several reasons this for now at least is not just an Enum which would make the process a lot easier. It is a string that can return two different values.

Is there any way to decorate the property so that the options are available in Swagger just as if it had been an Enum? For Enums we can use the MapType on startup, but this is just a string so it's not a type we can map perse.

This is how we have done it with Enums previously:

c.MapType<PaginationSessionType>(() => new OpenApiSchema
{
  Type = "string",
  Enum = typeof(PaginationSessionType).GetEnumNames()
         .Select(name => new OpenApiString(name)).Cast<IOpenApiAny>().ToList()
});

preview

Upvotes: 2

Views: 1642

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17664

http://swagger-net-test.azurewebsites.net/swagger/ui/index#/TestStringEnum/TestStringEnum_Post

enter image description here

I was able to do what you need with "swagger": "2.0" not 100% sure with the version you are using... At that time I got what I needed with the RegularExpression decorator.

here is the code that generates that:
https://github.com/heldersepu/Swagger-Net-Test/blob/master/Swagger_Test/Controllers/TestStringEnumController.cs

using System.Web.Http;
using System.ComponentModel.DataAnnotations;

namespace Swagger_Test.Controllers
{
    public class MyEndpointRequestClass
    {
        [RegularExpression("^(dark-blue|dark-red|light-blue|light-red)")]
        public string StringEnumColor { get; set; }

        [RegularExpression("^(high|medium|low)")]
        public string Transparency { get; set; }

        public string Name { get; set; }
    }

    public class TestStringEnumController : ApiController
    {
        public string Post([FromUri] MyEndpointRequestClass r)
        {
            return r.StringEnumColor;
        }

        public string Get([RegularExpression("^(uno|due)")]string x)
        {
            return x;
        }
    }
}

the relevant swagger.json from that is:

...
    "MyEndpointRequestClass": {
      "properties": {
        "StringEnumColor": {
          "type": "string",
          "pattern": "^(dark-blue|dark-red|light-blue|light-red)"
        },
        "Transparency": {
          "type": "string",
          "pattern": "^(high|medium|low)"
        },
        "Name": {
          "type": "string"
        }
      },
      "xml": {
        "name": "MyEndpointRequestClass"
      },
      "type": "object"
    },
...

This might not answer you question but hopefully it sends you on the right direction

Upvotes: 0

Related Questions