Swashbuckle Swagger - How to annotate content types?

前端 未结 4 836
南方客
南方客 2020-12-16 12:02

How do I annotate my ASP.NET WebAPI actions so that the swagger metadata includes the content-types that my resources support?

Specifically, I want the documentation

4条回答
  •  盖世英雄少女心
    2020-12-16 12:46

    Extending @VisualBean's answer.

    On a Controller's API method, you could use the code below to set an Attribute like:

    [SwaggerResponseContentType(responseType:"application/pdf", Exclusive=true)]
    public HttpResponseMessage GetAuthorityForm(string id)
    {
    ....
    

    Note: 'Exclusive=true' will remove all other content types, otherwise using the new Attribute will add a new Response Content Type in the Swagger UI drop down. It will NOT modify your Controller or API, just the documentation.

    SwaggerConfig.cs

     GlobalConfiguration.Configuration
                .EnableSwagger(c =>
     // Set filter to apply Custom Content Types to operations
     //
     c.OperationFilter();
    

    SwaggerResponseContentTypeAttribute.cs

    /// 
    /// SwaggerResponseContentTypeAttribute
    /// 
    [AttributeUsage(AttributeTargets.Method)]
    public sealed class SwaggerResponseContentTypeAttribute : Attribute
    {
        /// 
        /// SwaggerResponseContentTypeAttribute
        /// 
        /// 
        public SwaggerResponseContentTypeAttribute(string responseType)
        {
            ResponseType = responseType;
        }
        /// 
        /// Response Content Type
        /// 
        public string ResponseType { get; private set; }
    
        /// 
        /// Remove all other Response Content Types
        /// 
        public bool Exclusive { get; set; }
    }
    

    ResponseContentTypeOperationFilter.cs

    public class ResponseContentTypeOperationFilter : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var requestAttributes = apiDescription.GetControllerAndActionAttributes().FirstOrDefault();
    
            if (requestAttributes != null)
            {
                if (requestAttributes.Exclusive)
                    operation.produces.Clear();
    
                operation.produces.Add(requestAttributes.ResponseType);
            }
        }
    }
    

提交回复
热议问题