SkyN
SkyN

Reputation: 1533

How to set MaxLengthAttribute for IEnumerable which is returned from method (for generate swagger maxItems attribute)

I have a controller method that returns an array:

[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    //[MaxLength(10)]   // <- !!!!!!!!!!!!!!
    public  IEnumerable<WeatherForecast> Get([FromQuery] WeatherForecastQuery query)
...

a swagger spec has been generated for this controller which describes an array of responses without min/maxItems attributes

  ...
  "responses": {
      "200": {
        "description": "Success",
        "content": {
          "application/json": {
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/components/schemas/WeatherForecast"
              },
              //minItems: 1,   // <- I want it
              //maxItems: 10,  // <- I want it
            }}}}}
  ...

How can I add min/maxItems attributes to the method return array?

Upvotes: 1

Views: 1328

Answers (2)

TraderMoe
TraderMoe

Reputation: 84

You have to Put the Data Annotation [MaxLength(10)] to your WeatherForecastQuery object. I think this object contains the IEnumerable?

UPDATE

If i now understand correctly you want to return a maximum of 10 entries.

You could return a new object like this

public class GetWeatherForecastResponse {
     [MaxLength(10)]
     public IEnumerable<WeatherForecast> Result { get; set; }
}

then your controller should look like this

[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public GetWeatherForecastResponse Get([FromQuery] WeatherForecastQuery query)
...

Upvotes: 0

AnGG
AnGG

Reputation: 831

MaxLengthAttribute is not a method allowed attribute,

the targets of it are

[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property, AllowMultiple=false)]

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute?view=netcore-3.1

See also :

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1747

Upvotes: 3

Related Questions