【问题标题】:Html Example Response with Swagger and Swashbuckle带有 Swagger 和 Swashbuckle 的 Html 示例响应
【发布时间】:2018-02-28 11:01:48
【问题描述】:

我有一个 .NET Web API 2 应用程序,它带有一个返回 HTML 的控制器方法。我想在 swagger 文档中提供示例 HTML,但我无法显示任何内容。这就是我所拥有的:

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

但是,招摇的示例响应中没有显示任何内容。我在这里缺少任何配置吗?

【问题讨论】:

  • 我尝试了您的代码,毕竟我也无法在 swagger 中获得示例,但我注意到一些事情:1. 注释 [SwaggerResponseExample] 需要一个 HttpStatusCode 作为第一个参数。 2. 第二个参数需要是IExamplesProvider 类型,所以ExampleProvider 类应该实现IExamplesProvider 3. 方法应该是GetExamples() 而不是GetExample()。我使用 3.8 版的 Swashbuckle.Examples 对其进行了测试。你有不同的版本吗?至少我能得到对象的例子,但不能得到字符串的例子。

标签: c# asp.net-web-api2 swagger swagger-ui swashbuckle


【解决方案1】:

这里是 swashbuckle 的替代方法:Swagger-Net
我一直在为该项目添加新功能并修复错误。

您的代码将如下所示:

[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

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 2019-08-04
    • 2015-05-08
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多