[英]How to add a swagger example to the fields in the asp.net core?
Based on the Swagger documentation I must be able to add some examples for my class fields, something like:基于Swagger 文档,我必须能够为我的 class 字段添加一些示例,例如:
But I can't find any way to add these examples to my classes.但我找不到任何方法将这些示例添加到我的课程中。
You can enable XML Comments and then use the <example>
element to define an example.您可以启用XML 注释,然后使用
<example>
元素定义示例。 Here's an example of using an <example>
:这是使用
<example>
的示例:
public class CompanyValidationResponse
{
/// <example>1234</example>
public int CompanyId { get; set; }
/// <example>Damage, Inc</example>
public string CompanyName { get; set; }
}
To do this first you need to add XML documentation to your class.首先,您需要将 XML 文档添加到 class 中。 Here is an example.
这是一个例子。
namespace WebApplication44
{
/// <summary>
/// Display Weather Forecast
/// </summary>
public class WeatherForecast
{
/// <summary>
/// Date of the weather
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Temperature in Degree Celesuis
/// </summary>
public int TemperatureC { get; set; }
/// <summary>
/// Temperature in Fahrenheit
/// </summary>
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
/// <summary>
/// Summary of the Weather. It can be "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
/// </summary>
public string? Summary { get; set; }
}
}
Next, you need to enable the Documentation File > Generate a File containing API documentation option
in the Project Properties in Visual Studio - No need to change the location.接下来,您需要在 Visual Studio 的项目属性中启用
Documentation File > Generate a File containing API documentation option
- 无需更改位置。
Finally, modify the swagger generation code like this.最后,像这样修改swagger生成代码。
var xmlDoc = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "xml");
builder.Services.AddSwaggerGen(options => options.IncludeXmlComments(xmlDoc, true));
Then you will be able to see the Open API doc like this.然后您将能够看到像这样的 Open API 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.