.NET Core和Swagger API生成

17

我正在创建一个.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"});
    }
}
3个回答

31

我猜你指的是我代码中的这一行?var builder = services.AddMvcCore(); - JCircio
我无法使用AddMvc,因为会出现错误。这个项目是从一个空的WebAPI代码项目开始的。 - JCircio
然后尝试使用services.AddMvcCore().AddApiExplorer(); - Vladimir Arustamian
好的,那行了。我正在输入与你相同的回复。你最初的答案给了我所有需要的指引。太棒了,谢谢。现在,我要添加StructureMap来进行IoC,并查看它对Swagger有什么影响。在常规MVC项目中,我曾经遇到过这个问题。 - JCircio

0

如果您尝试将带有Swagger UI的AspNetCore MVC控制器添加到AspNetCore Web应用程序中,也会出现这些类型的错误。只需将它们分成两个不同的项目:mvc控制器和Web应用程序。


0

对于 ASP.NET Core 2.2,您应该编写:

services.AddMvcCore().AddApiExplorer();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接