Как отобразить SwaggerResponse в XML вместо JSON
Я хочу отобразить ответ в Swagger UI в формате XML вместо JSON. Как мне этого добиться? Это код, который я хочу адаптировать:
[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 ответ
Решение
Вы можете попробовать украсить метод атрибутом SwaggerProducesAttribute
как описано здесь:
[SwaggerProduces("text/xml")]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(FeedModel))]
public async Task<IActionResult> GetCompanyPostFeed(Guid companyId)
В соответствии с неприязнью ответов, содержащих только ссылки, я воспроизведу некоторые важные фрагменты этой статьи здесь:
[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();
}
}
Тогда в SwaggerConfig.cs вам понадобится что-то вроде:
config
.EnableSwagger(c =>
{
...
c.OperationFilter<ProducesOperationFilter>();
...
}