页面顶部的描述
要使用 Nswag 自定义 API 信息和描述,在 Startup.ConfigureServices 方法中,传递给 AddSwaggerDocument 方法的配置操作会添加作者、许可证和描述等信息:
services.AddSwaggerDocument(config =>
{
config.PostProcess = document =>
{
document.Info.Version = "v1";
document.Info.Title = "ToDo API";
document.Info.Description = "A simple ASP.NET Core web API";
document.Info.TermsOfService = "None";
document.Info.Contact = new NSwag.OpenApiContact
{
Name = "Shayne Boyer",
Email = string.Empty,
Url = "https://twitter.com/spboyer"
};
document.Info.License = new NSwag.OpenApiLicense
{
Name = "Use under LICX",
Url = "https://example.com/license"
};
};
});
Swagger UI 显示版本信息如下:
您可以通过将以下元素添加到操作标题来添加描述/示例。
使用<summary> 元素来描述端点。
使用<remarks> 元素补充<summary> 元素中指定的信息,并提供更强大的Swagger UI。 <remarks> 元素内容可以由文本、JSON 或 XML 组成。您也可以使用它来添加样本。
使用<param> 元素添加所需的参数。此外,您还可以在 Model 中使用 Data annotations 属性,它会改变 UI 行为。
使用<response> 元素来描述响应类型。
示例代码如下:
/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
/// POST /Todo
/// {
/// "id": 1,
/// "name": "Item1",
/// "isComplete": true
/// }
///
/// </remarks>
/// <param name="todoitem"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
#region snippet_CreateActionAttributes
[ProducesResponseType(StatusCodes.Status201Created)] // Created
[ProducesResponseType(StatusCodes.Status400BadRequest)] // BadRequest
#endregion snippet_CreateActionAttributes
#region snippet_CreateAction
[HttpPost]
public ActionResult<TodoItem> Create(TodoItem todoitem)
{
_context.TodoItems.Add(todoitem);
_context.SaveChanges();
return CreatedAtRoute("GetTodo", new { id = todoitem.Id }, todoitem);
}
Swagger UI 现在如下所示:
更多详细信息,请查看以下教程:
Customize API documentation using NSwag
Customize API info and description using Swashbuckle