1

I have a WebApi project and I am trying to implement Swagger. I am using Swahbuckle (5.2.1). In my actual project I have already an attribute for my responses :

[ResponseForApi(HttpStatusCode.OK)]

My problem is I am using Swashbuckle (5.2.1) and I don't want to put an other attribute for my methods. I know how to put responses on Swagger, I can use the 'XML Comments' or the attribute :

[SwaggerResponse(HttpStatusCode.OK)]

My question is : Is there a way to use 'SwaggerResponse' by calling 'ResponseForApi' ?

1 Answer 1

1

You could do this by wiring up your own IOperationFilter based on ApplySwaggerResponseAttributes -- that's the thing that scans for [SwaggerResponse]. Here's something I whipped up based on the Swashbuckle code https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/Swagger/Annotations/ApplySwaggerResponseAttributes.cs

public class ApplyResponseTypeAttributes : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { if (apiDescription.GetControllerAndActionAttributes<SwaggerResponseRemoveDefaultsAttribute>().Any()) { operation.responses.Clear(); } // SwaggerResponseAttribute trumps ResponseTypeAttribute var swaggerAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerResponseAttribute>(); if (!swaggerAttributes.Any()) { var responseAttributes = apiDescription.GetControllerAndActionAttributes<ResponseTypeAttribute>().OrderBy(attr => attr.ResponseType.Name); foreach (var attr in responseAttributes) { const string StatusCode = "200"; operation.responses[StatusCode] = new Response { description = InferDescriptionFrom(StatusCode), schema = (attr.ResponseType != null) ? schemaRegistry.GetOrRegister(attr.ResponseType) : null }; } } } private string InferDescriptionFrom(string statusCode) { HttpStatusCode enumValue; if (Enum.TryParse(statusCode, true, out enumValue)) { return enumValue.ToString(); } return null; } } 

In your swagger configuration in ./App_Start add the following to register this filter. It's actually pretty interesting putting a breakpoint on this so you can see how Swashbuckle works, it iterates through all your controller's actions.

c.OperationFilter<ApplyResponseTypeAttributes>(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.