services.AddSwaggerGen() giving error

后端 未结 4 401
情书的邮戳
情书的邮戳 2021-01-01 10:06

All I\'m trying to do is add swagger to an ASP.Net Core application. I\'m watching a tutorial and all I see them do is add services.AddSwaggerGen(); under the c

相关标签:
4条回答
  • 2021-01-01 10:46

    I had problem, that

    IServiceCollection does not contain a definition for 'AddSwaggerGen'

    I turnes out, that I installed Swashbuckle.AspNetCore.Swagger nuget package instead of Swashbuckle.AspNetCore.

    In .NET Core 3, there's some issues as discussed here. The solution is to add the following to the project file, replacing the prior version.

    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc2" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0-rc2" />
    
    0 讨论(0)
  • 2021-01-01 10:59

    This happens because the implementation of AddSwaggerGen() extension method in ASP.NET Core requires you to provide Action<SwaggerGenOptions> argument which serves as setup action. For example:

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });
    

    You can learn more on how to setup Swagger with ASP.NET Core app here.

    UPDATE: In previous versions they had the AddSwaggerGen() extension method accepting no arguments, but this call was accompanied with call ConfigureSwaggerDocument(Action<SwaggerGenOptions> setupAction). I guess they just got rid of ConfigureSwaggerDocument and added setup action to AddSwaggerGen() method. That being said it seems your tutorial shows how to setup obsolete version of the Swagger.

    0 讨论(0)
  • 2021-01-01 11:00

    Late answer, but as a new update on this question, I just noticed in order to make AddSwaggerGen works fine in .NET Core 3, you need to use OpenApiInfo instead of Info. So your new AddSwaggerGen should be something like this:

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "The API", Version = "v1" });
    });
    

    Also you need to add the following to your using directives:

    using Microsoft.OpenApi.Models;
    

    Read more here https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio

    0 讨论(0)
  • 2021-01-01 11:06

    For the .Net core project, you need to install Four packages. Better to use Nuget package manager so it takes appropriate needed versions.

    Microsoft.OpenApi
    Swashbuckle.AspNetCore.Swagger
    Swashbuckle.AspNetCore.SwaggerGen
    Swashbuckle.AspNetCore.SwaggerUI
    
    0 讨论(0)
提交回复
热议问题