How to display SwaggerResponse in XML instead of JSON

房东的猫 提交于 2021-01-29 14:29:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!