Swagger 未正确生成 api 文档

Swagger is not generating api documentation correctly

我有一个 asp.net 核心网络 api 项目,我使用的是 3.1 版。我安装了swagger包并进行了配置,一切正常,但是看不到swagger页面的API,这是为什么,这是我参考文档的配置信息

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddControllers();

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "ToDo API",
            Description = "A simple example ASP.NET Core Web API",
            TermsOfService = new Uri("https://example.com/terms"),
            Contact = new OpenApiContact
            {
                Name = "Shayne Boyer",
                Email = string.Empty,
                Url = new Uri("https://twitter.com/spboyer"),
            },
            License = new OpenApiLicense
            {
                Name = "Use under LICX",
                Url = new Uri("https://example.com/license"),
            }
        });

        // Set the comments path for the Swagger JSON and UI.
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}

public void Configure(IApplicationBuilder app)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger(c =>
    {
        c.SerializeAsV2 = true;
    });

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

我根据你的代码重现了问题。我自己创建了一个Controller,但是由于没有添加路由地址,第一次打开是这样的:

只有一个默认路由,但在我的项目中我添加了一个 HomeController,它也没有出现在 API。

 public class HomeController : Controller
    {

        [HttpGet]
     
        public string Index()
        {
            return "test";
        }
    }

这是因为我没有添加路由地址所以没有显示

[Route("api/[controller]")]
public class HomeController : Controller
{

    [HttpGet]
    [Route("test")]
    public string Index()
    {
        return "test";
    }
}

添加后:

不知道你是不是这个原因,如果不是,能详细说说你的步骤吗?或者提供一个界面,让您的 swagger 不显示 API.

参考文档:

Get started with Swashbuckle and ASP.NET Core