0

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

1 Answer 1

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>();
            ...
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but the method GetControllerAndActionAttributes does not exists, I use ASP.NET Core 2.1 and Swashbuckle.AspNetCore.Swagger 3.0.0
@frank_lbt - it's an extension method, and not that complicated; you may be able to roll your own for .NET Core: github.com/domaindrivendev/Swashbuckle/blob/master/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.