Search code examples
validationasp.net-coregetasp.net-core-webapiswagger-ui

NetCore SwaggerUI - Get Route - Validations for parameters are not displayed to user


I'm trying to define a type of "GET" route in my WebApi (Net 5) that use 2 route parameter and they require validations, the parameters come from the route. I need the same pattern multiple actions in other controllers too. So, i've tried to use the ValidationAttribute like we do in POST, SwaggerUI know when there is error with the parameters and know when the parameters are valid but doesn't show the errors.

ex:
/calendar/year/month

year must be between 2020 AND 2030
month must be between 1 AND 12

so, i've started with something like this

public class YearMonth
{
    [Range(2020, 2030, ErrorMessage = "The year must be between 2020 AND 2030")]
    public int Year { get; set; }

    [Range(1, 12, ErrorMessage = "The month must be between 1 AND 12")]
    public int Month { get; set; }
}

[HttpGet("{Year}/{Month}")]
public async Task<ActionResult<Calendar>> Get([FromRoute] YearMonth yearMonth)
{

}

My problem is that Swagger UI know the validation so it doesnt fire the request if the year or the month doesn't pass the validation. It show that the field is in error!

But there is nothing in the UI that show why there is an error or what is the error exactly!

enter image description here

Is there a way to add the validations errors?

Or is there a way to add a label to describe the validations?

When we post data to the API, it execute the request even if the object is not valid and return the HttpResponseMessage with the errors in it, I was expecting the same from the Get Method!

enter image description here


Solution

  • In your Swashbuckle configuration, use:

    app.UseSwaggerUI(c =>
    {
        ...
        c.ShowCommonExtensions();
    });
    

    This instructs Swagger UI to display the defined minimum and maximum values for input parameters.


    It show that the field is in error! But there is nothing in the UI that show why there is an error or what is the error exactly!

    If you hover over the red field it will show a tooltip with an error message like "value must be greater than 2020".