问题
I want to display a response in Swagger UI in XML format instead of JSON. How I can achieve this? This is the code I want to adapt:
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(FeedModel))]
public async Task<IActionResult> GetCompanyPostFeed(Guid companyId)
{
var feed = new FeedModel();
// Some database requests
return Content(feed, "text/xml", Encoding.UTF8);
}
回答1:
You could try decorating the method with an attribute SwaggerProducesAttribute
as described here:
[SwaggerProduces("text/xml")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(FeedModel))]
public async Task<IActionResult> GetCompanyPostFeed(Guid companyId)
In keeping with the dislike of link-only answers, I'll reproduce some of the relevant bits of that article here:
[AttributeUsage(AttributeTargets.Method)]
public class SwaggerProducesAttribute : Attribute
{
public SwaggerProducesAttribute(params string[] contentTypes)
{
this.ContentTypes = contentTypes;
}
public IEnumerable<string> ContentTypes { get; }
}
public class ProducesOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var attribute = apiDescription.GetControllerAndActionAttributes<SwaggerProducesAttribute>().SingleOrDefault();
if (attribute == null)
{
return;
}
operation.produces.Clear();
operation.produces = attribute.ContentTypes.ToList();
}
}
Then in SwaggerConfig.cs, you'll need something like:
config
.EnableSwagger(c =>
{
...
c.OperationFilter<ProducesOperationFilter>();
...
}
来源:https://stackoverflow.com/questions/52948105/how-to-display-swaggerresponse-in-xml-instead-of-json