Swagger 文档有空路径

Swagger doc has empty paths

我的 Swagger 文档没有正确生成,我有基本信息(标题、名称、许可证等)但我的路线上没有文档。

这是 Startup.cs 中的设置:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<APIContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddControllersWithViews();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "OpenWeb Challenge",
                Description = "A 'simple' example ASP.NET Core Web API",
                TermsOfService = new Uri("https://example.com/terms"),
                Contact = new OpenApiContact
                {
                    Name = "Anthony Da Silva Ferreira",
                    Email = string.Empty,
                    Url = new Uri("https://twitter.com/spboyer"),
                }
            });

            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            c.IncludeXmlComments(xmlPath);
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "OpenWebChallenge V1");
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

以及招摇的内容:

{
  "openapi": "3.0.1",
  "info": {
    "title": "OpenWeb Challenge",
    "description": "A 'simple' example ASP.NET Core Web API",
    "termsOfService": "https://example.com/terms",
    "contact": {
      "name": "Anthony Da Silva Ferreira",
      "url": "https://twitter.com/spboyer",
      "email": ""
    },
    "license": {
      "name": "Licence",
      "url": "https://example.com/license"
    },
    "version": "v1"
  },
  "paths": { },
  "components": { }
}

控制器示例:

public class ContactsController : Controller
{
    private readonly APIContext _context;

    public ContactsController(APIContext context)
    {
        _context = context;
    }

    // GET: Contacts
    public async Task<IActionResult> Index()
    {
        return View(await _context.Contacts.ToListAsync());
    }

    // GET: Contacts/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var contact = await _context.Contacts
            .Include(c => c.ContactSkills)
                .ThenInclude(cs => cs.Skill)
            .AsNoTracking()
            .FirstOrDefaultAsync(m => m.Id == id);

        if (contact == null)
        {
            return NotFound();
        }

        return View(contact);
    }
}

我是不是遗漏了什么配置?这是我第一次从头开始创建 API。

您是否已将 PropertyGroup 添加到 PROJECT_NAME.csproj 文件?

<PropertyGroup>
   <GenerateDocumentationFile>true</GenerateDocumentationFile>
   <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

没有它,编译器将不会生成文档文件。

Microsoft Documentation

编辑

在文档中它说:“您必须对您想要在 Swagger 文档中表示的任何控制器使用属性路由”Link。 所以对于你的控制器来说,它将是:

[Route("api/contacts")]
public class ContactsController : Controller
{
...

    // GET: Contacts
    [HttpGet("")]
    public async Task<IActionResult> Index()
    {
    ...
    }

    // GET: Contacts/Details/5
    [HttpGet("/details/{id?}")]
    public async Task<IActionResult> Details([FromRoute] int? id)
    {
        ...
    }
}

编辑

我使用了错误的路由模板语法:

[HttpGet("/details/:id?")] -> [HttpGet("/details/{id?}")]

?对于可选参数

从您的代码来看,ContactsController 似乎是一个 MVC 控制器(它将 return 视图),而不是 API 控制器。

The Swagger (OpenAPI) 是一种与语言无关的规范,用于描述 REST APIs,而不是 MVC 控制器。因此,它不会为 MVC 控制器生成 Swagger 文档。尝试添加一个 API 控制器,然后使用 Swagger 添加 API 信息和描述。

更多关于使用Swagger的详细信息,查看Get started with Swashbuckle and ASP.NET Core