简体   繁体   中英

C# Swashbuckle SwaggerResponseAttribute

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' ?

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM