Search code examples
jsonasp.net-web-apiswagger-uiswagger-2.0swashbuckle

Swashbuckle, Swagger Pattern and Format annotation or XML comment


I'am trying to add the format and/or pattern keywords in my Swagger documentation. I'am using Swashbuckle and currenlty I'am using XML Comments to insert descriptions for my different fields. For example: The controller:

/// <summary>
/// Shows a list with states
/// </summary>
/// <param name="id">The state ID</param>
/// <returns>Offers the state</returns>
[HttpGet("id", Name = "Get")]
public async Task<ActionResult<State>> GetState(string id)
{
State result = GetState(id);
return Ok(result);
}

I want the swagger documentation to show the pattern keyword with the regex expression:

'^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$'

Is it possible to add this documentation while using XML comments or annotations. I'd like to ask the same for the format keyword. For example: 'format: date-time'

Are these things possible using XML comments or annotations with Swashbuckle to auto generate Swagger documentation or would this require a static swagger file?


Solution

  • On the project there is an example how to use it for models: https://github.com/domaindrivendev/Swashbuckle/blob/5489aca0d2dd7946f5569341f621f581720d4634/Swashbuckle.Dummy.Core/Controllers/MetadataAnnotatedTypesController.cs#L21

    public class PaymentMetadata
    {
        [Required]
        public decimal Amount { get; set; }
    
        [Required, RegularExpression("^[3-6]?\\d{12,15}$")]
        public string CardNumber { get; set; }
    
        [Required, Range(1, 12)]
        public int ExpMonth { get; set; }
    
        [Required, Range(14, 99)]
        public int ExpYear { get; set; }
    
        [StringLength(500, MinimumLength = 10)]
        public string Note { get; set; }
    }
    

    For a primitive like in your case I'm not sure that is fully supported, you can try with something like:

    public async Task<ActionResult<State>> GetState([RegularExpression("PATTERN")]string id)
    

    If that does not work you can inject it using an IDocumentFilter