Automatically generate default 200 OK response whi

2019-07-22 11:32发布

问题:

According to #216, Swashbuckle will automatically generate a 200 success response as the default behavior, or otherwise expects all response types to be specified.

I'd like to be able to add a 404/400 error response to some endpoints in the XML comments while keeping the 200 success responses for all endpoints, including those with a 404/400 error response.

Is it possible to make Swashbuckle continue to automatically generate a 200 success response for all endpoints even when an error response is specified?

Edit: I added an operation filter to programmatically add the missing 200 responses, which resolved the missing model schemas, but still doesn't really answer my original question about whether there's a way to keep Swashbuckle's automatic generation of 200 success responses

class CustomOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responses = operation.responses;
        if (responses.ContainsKey("404") || responses.ContainsKey("400"))
        {
            responses.Add("200", new Response()
            {
                description = "OK",
                schema = (schemaRegistry.GetOrRegister(apiDescription.ActionDescriptor.ReturnType))
            });
        }
    }
}

回答1:

Here is a workaround to add missing 200 success responses to endpoints that have specified error responses:

class CustomOperationFilter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var responses = operation.responses;
        if (!responses.ContainsKey("200"))
        {
            if (apiDescription.ActionDescriptor.ReturnType != null)
            {
                responses.Add("200", new Response()
                {
                    description = "OK",
                    schema = (schemaRegistry.GetOrRegister(apiDescription.ActionDescriptor.ReturnType))
                });
            }
        }
    }
}