Rob
Rob

Reputation: 7217

ASP.net Core - SwaggerResponseExample not outputting specified example

I' using ASP.net Core and swagger, I have created the following method and verbose documentation:

/// <summary>Creates a package with the requested information.</summary>
/// <param name="createPackage">The package information to create.</param>
/// <response code="201" cref="PackageCreatedExample">Created</response>
/// <returns><see cref="PackageCreated"/> package created.</returns>
[HttpPost]
[SwaggerResponse(201, "Package created", typeof(PackageCreated))]
[SwaggerResponse(400, "Validation failure", typeof(ApiErrorResult))]
[SwaggerResponseExample(201, typeof(PackageCreatedExample))]
public async Task<IActionResult> CreatePackage(PackageCreate createPackage)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(new ApiErrorResult(ModelState));
    }

    var createdPackageInfo = new PackageCreated();

    // Created item and location returned.
    return CreatedAtAction(nameof(GetPackage), new { createdPackageInfo.Id, Version = "2" }, createdPackageInfo);
}

I am trying to get an example response to appear in swagger but it always defaults the response sample as follows:

enter image description here

As you can see from the code above, I created a "PackageCreatedExample" class that I want to be picked up and used in swagger but it's just being ignored. I tried using comments response code="201" cref="PackageCreatedExample" and wrote the SwaggerResponseExample attribute, but neither get picked up. Here's my example code:

public class PackageCreatedExample : IExamplesProvider<PackageCreated>
    {
        public PackageCreated GetExamples()
        {
            return new PackageCreated {
                Outcome = "PackageCreated",
                Reference = "6178",
                ShippingDocumentation = new List<Documentation> {
                    new Documentation {
                        Document = "JVBERi0xLjMNCjEgMCBvYmoNCjw8DQovVHlwZSAvQ2F...",
                        Format = "Pdf",
                        Type = DocumentationType.TYPE3
                    }
                },
                ReturnsDocumentation = new List<Documentation> {
                    new Documentation {
                        Document = "YmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL1BhZ2VzIDQgMJVBERi0xLjMNCjEgMCBv...",
                        Format = "doc",
                        Type = DocumentationType.TYPE4
                    }
                }
            };
        }
    }

What am I doing wrong?

Thanks in advance for any pointers!

Upvotes: 3

Views: 4924

Answers (1)

aliras
aliras

Reputation: 424

According to the author, this method should not be used anymore (link). This section of the official readme describes the way how the descriptions and examples should be handled.

In short, you have to

  1. Remove all the annotations and use the followings instead:
/// <summary>Creates a package with the requested information.</summary>
/// <param name="createPackage">The package information to create.</param>
/// <returns>package created.</returns>
/// <response code="201">Created</response>
/// <response code="400">Validation failure</response>
[HttpPost]
[ProducesResponseType(typeof(PackageCreated), 201)]
[ProducesResponseType(typeof(ApiErrorResult), 400)]
public async Task<IActionResult> CreatePackage(PackageCreate createPackage)       
  1. Enable generating XML documentation under Project -> Properties -> Build tab -> Check XML documentation file in the Output section
  2. Configure swagger to use the generated XML file
services.AddSwaggerGen(c =>
{
  c.SwaggerDoc("v1",
      new OpenApiInfo
      {
          Title = "My API - V1",
          Version = "v1"
      }
   );

   var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
   c.IncludeXmlComments(filePath);
}
  1. Add example comments to the properties of your input model classes:

PackageCreate.cs

public PackageCreate 
{
  // Built-in type
  /// <summary>
  /// Outcome value
  /// </summary>
  /// <example>PackageCreated</example>
  public string Outcome { get; set; }

  // Custom class -> comment its properties in Documentation.cs
  public Documentation { get; set; }

  // Array type -> comment the properties in Documentation.cs
  public IList<Documentation> { get; set; }
}

Documentation.cs:

public Documentation
{
  /// <summary>
  /// Document name
  /// </summary>
  /// <example>YmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL1BhZ2VzIDQgMJVBERi0xLjMNCjEgMCBv</example>
  public string Document { get; set; }

  /// <summary>
  /// Document format
  /// </summary>
  /// <example>doc</example> 
  public string Format { get; set; }
}

Upvotes: 5

Related Questions