为什么虚张声势的示例值不起作用?

Yor*_*oro 3 .net-core asp.net-core swashbuckle.aspnetcore

这里我example="this does not work"为 swashbuckle 框架添加了 XML 文档参数。

/// <summary>Gets a user by id.</summary>
/// <param name="id" example="this does not work">The id of user.</param>
/// <returns>got user.</returns>
[HttpGet("Get")]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(AppException), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Get(string id)
{
    return HandleResult(await _userServices.GetUserAsync(id));
}
Run Code Online (Sandbox Code Playgroud)

但示例值不会出现在 Swagger UI 中。

在此输入图像描述

我应该去哪里寻找问题?

Anu*_*raj 5

不幸的是,开箱即用的 Swashbuckle 不支持示例标签/属性。您需要编写一个操作过滤器并实现您自己的。或者您可以使用Swashbuckle.AspNetCore.Filtersnuget 包。

您需要在program.cs 文件中添加以下代码。

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
});
//For Example tag support
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());
Run Code Online (Sandbox Code Playgroud)

一旦运行该应用程序,您将能够在 swagger 文档中看到这样的示例。

Swagger 文档与示例

  • 找到了为什么它不起作用。我将项目 `app.UseSwagger(c =&gt; c.SerializeAsV2 = true)` 更改为 `app.UseSwagger()` ,现在一切正常。感谢您的解决方案! (2认同)