Html Example Response with Swagger and Swashbuckle

2019-08-20 03:40发布

I have a .NET Web API 2 app, with a controller method that returns HTML. I want to provide sample HTML in the swagger docs, but I can't get anything to show. This is what I have:

[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(string))]
[SwaggerResponse(HttpStatusCode.NotFound)]
[SwaggerResponseContentType("text/html", Exclusive = true)]
[SwaggerResponseExamples(typeof(string), typeof(ExampleProvider))]
public async Task<HttpResponseMessage> Get(Guid id)
{
    var example = GetExample();

    return new HttpResponseMessage
    {
        Content = new StringContent(example, Encoding.UTF8, "text/html")
    };
}

public class ExampleProvider
{
    public object GetExample()
    {
        return @"
                <!DOCTYPE html>
                <html>
                    <head></head>
                    <body>
                        <h1>hello</h1>
                    </body>
                </html>";
    }
}

However, nothing shows up in the example response in swagger. Am I missing any configuration here?

1条回答
走好不送
2楼-- · 2019-08-20 04:09

Here is an alternative to swashbuckle: Swagger-Net
I've been working on that project adding new features and fixing bugs.

Your code will look like:

[SwaggerResponse(HttpStatusCode.OK, type: typeof(string), mediaType: "text/html", examples: EXAMPLE)]
public async Task<HttpResponseMessage> Get()
{
    return new HttpResponseMessage
    {
        Content = new StringContent(EXAMPLE, Encoding.UTF8, "text/html")
    };
}

const string EXAMPLE = @"
    <!DOCTYPE html>
    <html>
        <head></head>
        <body>
            <h1>hello</h1>
        </body>
    </html>";

And here is how that will look like on the Swagger-UI:
http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=HtmlExample#/HtmlExample/HtmlExample_Get

查看更多
登录 后发表回答