簡體   English   中英

.NET Core 和 Swagger API 生成

[英].NET Core and Swagger API generation

我正在創建一個准系統 .NET Core web api 項目(從下面的空白模板開始) https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-網核/

下面的代碼運行良好,直到我添加了 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"});
    }
}

解決方案:在 Startup.cs 中使用 AddMvc() 而不是 AddMvcCore() 它將起作用。

或寫:

services.AddMvcCore().AddApiExplorer();

這些鏈接可以幫助:

沒有注冊“Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory”類型的服務

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/299

對於 ASP.NET Core 2.2,您應該編寫:

services.AddMvcCore().AddApiExplorer();

如果您嘗試將帶有 Swagger UI 的 AspNetCore MVC 控制器添加到 AspNetCore Web 應用程序中,也會出現這些類型的錯誤。 只需將它們分成兩個不同的項目:mvc 控制器和 Web 應用程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM