当前位置: 首页 > 知识库问答 >
问题:

Swagger(ASP.NET核心)有控制器描述吗?

宁弘亮
2023-03-14

共有1个答案

戴靖
2023-03-14

如果您使用的是SwashBuckle4.0.x和ASP.NET Core2.x,您可能有类似的功能,它也可以通过包含Swashbuckle.aspnetcore.Annotations的NuGet包来工作。

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Annotations;

namespace MyExample.Controllers
{
/// <summary>
/// Example of a .NET Core controller based on the controller name
/// api/[controller] on ValuesController becomes api/values
/// endpoint: "/Values" from [controller] and name of controller , which is "ValuesController"
/// </summary>
[Route("[controller]")]
[ApiController]
[SwaggerTag("This is an example controller generated by ASP.NET Core 2.x")]
public class ValuesController : ControllerBase
{
...
}

然后ConfigureServices方法中的Startup.cs swagger代码如下所示(编辑为包含Iain Carlin的贡献,以包含控制器头注释):

services.AddSwaggerGen(c =>
{
    // Set Title and version
    c.SwaggerDoc("v1", new Info { Title = "My Example API", Version = "v1", Description = "The API for my application" });
    // Set the comments path for the Swagger JSON and UI.
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    // pick comments from classes, including controller summary comments
    c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true); 
    // _OR_ enable the annotations on Controller classes [SwaggerTag], if no class comments present
    c.EnableAnnotations();
});

然后我的控制器会被装饰

 类似资料: