0

I found this nice type-safe enum pattern, and i think is very cool.

The class does have only public static properties and a private constructor, and can implicitly inferred from a string. I'm using it as a property of my model which get model-binded correctly in asp.net core web api controller when I pass a string. Passing invalid string values also work fine as the binder is able to set ModelSate=false. I have something in this line:

class Mymodel
{
   public TypeSafeEnum TypeSafeEnum { get; set; }
   public string Name { get; set; }
   // the rest of props
}

Throwing in some swagger api documentation, the property is seen as an object, hence swagger trying to help will give example input model as:

{
  "typeSafeEnum": {},
  "name": "string",
  // the rest
}

The swagger just see an object with no public properties.

Is there a form of telling swagger that I'm actually expecting a string? or will I be deceiving my clients as not all string values are valid? But again how do I provide meaningful hint?

dbc
  • 104,963
  • 20
  • 228
  • 340
rethabile
  • 3,029
  • 6
  • 34
  • 68
  • How are you generating your swagger documentation? If you are using [Swashbuckle.AspNetCore](https://github.com/domaindrivendev/Swashbuckle.AspNetCore), then this link seems relevant: [Override Schema for Specific Types](https://github.com/domaindrivendev/Swashbuckle.AspNetCore#override-schema-for-specific-types). – dbc Jul 27 '17 at 01:07

1 Answers1

0

If the property is a string, Swagger will document it as a string. Strings can accept anything obviously. If you want only certain values passed in to the string and you want it clearly documented in the Swagger doc, use an enum. You can also use property validators like regex (or write your own custom one), but they don't get documented, they are only displayed when the validation fails. I.e. for regex, if it fails the regex, it'll return a Json that says this field failed this regex, but the regex doesn't show up in the swagger doc.

SledgeHammer
  • 7,338
  • 6
  • 41
  • 86