带有Swagger和Swashbuckle的HTML示例响应 [英] Html Example Response with Swagger and Swashbuckle

查看:155
本文介绍了带有Swagger和Swashbuckle的HTML示例响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET Web API 2应用程序,其控制器方法返回HTML.我想在招摇的文档中提供示例HTML,但是我什么也没显示.这就是我所拥有的:

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?

推荐答案

这里是swashbuckle的替代方法:

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

您的代码如下:

[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>";

这是Swagger-UI的外观:
http://swagger-net-test .azurewebsites.net/swagger/ui/index?filter = HtmlExample#/HtmlExample/HtmlExample_Get

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

这篇关于带有Swagger和Swashbuckle的HTML示例响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆