如何在 asp.net 核心的字段中添加一个 swagger 示例?

How to add a swagger example to the fields in the asp.net core?

基于 the Swagger documentation 我必须能够为我的 class 字段添加一些示例,例如:

但我找不到任何方法将这些示例添加到我的 classes 中。

您可以启用 XML Comments,然后使用 <example> 元素来定义示例。这是使用 <example>:

的示例
public class CompanyValidationResponse
{
    /// <example>1234</example>
    public int CompanyId { get; set; }

    /// <example>Damage, Inc</example>
    public string CompanyName { get; set; }
}

首先,您需要将 XML 文档添加到您的 class。这是一个例子。

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

接下来,您需要在 Visual Studio 的项目属性中启用 Documentation File > Generate a File containing API documentation option - 无需更改位置。

最后把swagger生成代码修改成这样

var xmlDoc = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "xml");
builder.Services.AddSwaggerGen(options => options.IncludeXmlComments(xmlDoc, true));

然后您将能够看到这样的打开 API 文档。