2

I'm currently working this on ASP.NET Core 3.0 using Swashbuckle.AspNetCore, but I would like to know the case for OpenAPI 3.0 Specification in case anyone else knows better.

I try currently set the specification with Nuget library so that normally return values are content-type: application/json, but in exceptional cases content-type: application/problem+json. This does not appear to be possible out-of-the-box in ASP.NET Core 3.0 & Swashbuckle (or I sorely missed it). Is this correct? If not out-of-the-box, what could be the way to do this systematically?

Is it possible in OpenAPI specification? I'm inclined to believe it probably is, but missed it while trying to glance through the specification.

Here is a image for the automatically generated documentation and HTTP 400 case I would like show only application/problem+json as the return value.

Swashbuckle generated UI

Veksi
  • 3,556
  • 3
  • 30
  • 69

1 Answers1

2

This can be done with an IOperationFilter,you could custom like below:

1.CustomResponseType:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;    
public class CustomResponseType : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Responses.ContainsKey("400")) {
            operation.Responses.Clear();
        }
        var data = new OpenApiResponse
        {
            Description = "Bad Request",
            Content = new Dictionary<string, OpenApiMediaType>
            {
                ["application/problem+json"] = new OpenApiMediaType(),
            }
        };
        operation.Responses.Add("400", data);
    }
}

2.Startup.cs:

services.AddSwaggerGen(c =>
     {
          c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
          c.OperationFilter<CustomResponseType>();
     });

3.Result:

enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72
  • I'm inclined to accept this, but let I get to computer first in about four hours. A question that occurred, do you happen to know if this `IOperationFilter` can be made visible as a code construct (not comments etc., which is better than nothing) on the call site, in the controller in this case? It would be clearer like that, though I appreciate if not possible. – Veksi Oct 31 '19 at 11:55