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
@OzBob's answer assumes you only want to add a single attribute to a method. If you want to add and document more than one content types for the same method, you can use the following:
SwaggerResponseContentTypeAttribute.cs
///
/// SwaggerResponseContentTypeAttribute
///
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public 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();
foreach (var requestAttribute in requestAttributes)
{
if (requestAttribute.Exclusive)
{
operation.produces.Clear();
}
operation.produces.Add(requestAttribute.ResponseType);
}
}
}
Note that when you have multiple attributes on the same method and you want to replace the existing content types, you should set Exclusive = true
on the first attribute only. Otherwise, you won't get all the attributes into the documentation.