首页 文章

.NET Core和Swagger API生成

提问于
浏览
4

我正在创建一个准系统.NET Core web api项目(从下面的空白模板开始)https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-net-core/

下面的代码工作正常,直到我添加了Swashbuckle.AspNetCore(以及下面的配置代码),现在我们得到这个错误

InvalidOperationException:没有注册类型为“Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionGroupCollectionProvider”的服务 .

有任何想法吗?

请注意:我们没有使用“builder.AppMvc()”,因为我们正在尝试尽可能减少这个API .

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        var builder = services.AddMvcCore();

        builder.AddAuthorization();
        builder.AddFormatterMappings();
        builder.AddJsonFormatters();
        builder.AddCors();

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();



        app.UseMvc();


        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // 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");
        });
    }
}

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new[] {"value1", "value2"});
    }
}

1 回答

相关问题