.NET Core 2和SwashBuckle Swagger UI无法显示

11

我跟着几个教程走了一遍,在工作中这个能够正常运行,但是出现了一个问题,即无法显示用户界面,但是Swagger Json已经被创建了。最后一个我看的教程在这里

我的设置如下:

Nuget包: Swashbuckle.AspNetCore(1.0.0)

ConfigureServices 方法:

services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1",
                    new Info
                    {
                        Title = "MediatR Example",
                        Version = "v1",
                        Description = "Trying out the MediatR library to simplify Request and Response logic.",
                        TermsOfService = "WTFPL",
                        Contact = new Contact
                        {
                            Email = "",
                            Name = "",
                            Url = "https://github.com/CubicleJockey/MediatR-Playground"
                        }
                    }
                );

                var xmlDocFile = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, @"MediatR-Messages.Api.xml");
                options.IncludeXmlComments(xmlDocFile);
                options.DescribeAllEnumsAsStrings();
            });

配置方法:

 app.UseMvcWithDefaultRoute();

            // 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(config =>
            {
                config.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
            });

launchSettings.json

"IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger/",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },

运行并访问Swagger JSON URL 会生成相应的 JSON:

   {
   "swagger":"2.0",
   "info":{
      "version":"v1",
      "title":"MediatR Example",
      "description":"Trying out the MediatR library to simplify Request and Response logic.",
      "termsOfService":"WTFPL",
      "contact":{
         "name":"André Davis",
         "url":"https://github.com/CubicleJockey/MediatR-Playground",
         "email":"davis.andre@gmail.com"
      }
   },
   "basePath":"/",
   "paths":{
      "/api/Addition":{
         "get":{
            "tags":[
               "Addition"
            ],
            "summary":"Get Methods that takes two numbers and gets the sum.",
            "operationId":"ApiAdditionGet",
            "consumes":[

            ],
            "produces":[
               "text/plain",
               "application/json",
               "text/json"
            ],
            "parameters":[
               {
                  "name":"left",
                  "in":"query",
                  "description":"Left hand side of the equation.",
                  "required":false,
                  "type":"integer",
                  "format":"int32"
               },
               {
                  "name":"right",
                  "in":"query",
                  "description":"Right hand side of the equation.",
                  "required":false,
                  "type":"integer",
                  "format":"int32"
               }
            ],
            "responses":{
               "200":{
                  "description":"Success",
                  "schema":{
                     "$ref":"#/definitions/Task[AdditionResponse]"
                  }
               }
            }
         }
      }
   },
   "definitions":{
      "Task[AdditionResponse]":{
         "type":"object",
         "properties":{
            "result":{
               "$ref":"#/definitions/AdditionResponse",
               "readOnly":true
            },
            "id":{
               "format":"int32",
               "type":"integer",
               "readOnly":true
            },
            "exception":{
               "type":"object",
               "readOnly":true
            },
            "status":{
               "enum":[
                  "Created",
                  "WaitingForActivation",
                  "WaitingToRun",
                  "Running",
                  "WaitingForChildrenToComplete",
                  "RanToCompletion",
                  "Canceled",
                  "Faulted"
               ],
               "type":"string",
               "readOnly":true
            },
            "isCanceled":{
               "type":"boolean",
               "readOnly":true
            },
            "isCompleted":{
               "type":"boolean",
               "readOnly":true
            },
            "isCompletedSuccessfully":{
               "type":"boolean",
               "readOnly":true
            },
            "creationOptions":{
               "enum":[
                  "None",
                  "PreferFairness",
                  "LongRunning",
                  "AttachedToParent",
                  "DenyChildAttach",
                  "HideScheduler",
                  "RunContinuationsAsynchronously"
               ],
               "type":"string",
               "readOnly":true
            },
            "asyncState":{
               "type":"object",
               "readOnly":true
            },
            "isFaulted":{
               "type":"boolean",
               "readOnly":true
            }
         }
      },
      "AdditionResponse":{
         "type":"object",
         "properties":{
            "answer":{
               "format":"int32",
               "type":"integer",
               "readOnly":true
            },
            "equation":{
               "type":"string",
               "readOnly":true
            }
         }
      }
   },
   "securityDefinitions":{

   }
}

当访问默认的Swagger UI url时,我遇到了404错误。尝试了几个变化:

  1. localhost:64881/swagger/
  2. localhost:64881/swagger/ui
  3. localhost:64881/swagger/index.html
  4. localhost:64881/swagger/ui/index.html

以上所有都返回404。这些在不同的版本中曾经起作用过。我错过了什么?

完整的源代码可以在我的GitHub 这里 找到。这是一个针对此问题的分支,因此代码与我的请求相匹配。

6个回答

11
下载并测试您的代码后,发现您必须将以下NuGet包添加到您的项目中:
Microsoft.AspNetCore.StaticFiles

你可以通过NuGet Manager或者将以下行添加到你的.csproj文件来完成此操作:<ItemGroup>

<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" /> 

来源: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/438


1
如果您使用了 Microsoft.AspNetCore.All 元包替换了所有的 Microsoft.AspNetCore.* 包,则不需要添加 Microsoft.AspNetCore.StaticFiles 包。 - Dmitry Pavlov
4
对我来说非常有效 :-) 说实话,与安装 Microsoft.AspNetCore.All 相比,我更喜欢这种方法,因为它可以极大地增加项目的依赖项。 - hobnob
Microsoft.AspNetCore.StaticFiles 2.0.0包与netcoreapp1.1不兼容。 - Enrico

10

对我有效的解决方法:

  1. 删除部署文件夹中所有旧文件(我试过使用IIS,也适用于其他托管类型)。
  2. 使用Microsoft.AspNetCore.All元包替换所有的Microsoft.AspNetCore.*软件包 - 详情请参见此文章
  3. [可选]如果出现副作用,只需重新安装Swashbuckle.AspNetCore软件包(无需其他Swashbuckle.AspNetCore.*软件包)。
  4. 确保在项目文件中有以下2个软件包(只需要这样就足够了):

    • PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0"
    • PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0"
  5. 发布(或通过复制文件进行部署)到您的部署文件夹。 现在应该可以工作了。

注意:如果API中存在重复的模型名称,有时会失败(在这种情况下,浏览器会显示一些不清楚的错误);)


2
我还需要删除 .vs 解决方案文件夹。 - Mathias Rönnlund
对于 ASP.NET Core 2.1 及以上版本,元包 Microsoft.AspNetCore.All 已被替换为 Microsoft.AspNetCore.App - Dmitry Pavlov

5
尝试删除.vs文件夹。在升级到ASP.NET Core 2.1后,这对我有用。

1
我曾经遇到过同样的问题,花了几个小时才发现是使用了Chrome认为不安全的端口(这个提示文字很难注意到)。这对未来可能会有所帮助。

1

我曾遇到同样的问题,我的问题是缺少HttpMethod binding。

System.NotSupportedException:Swagger 2.0需要显式的HttpMethod绑定来执行操作。


1

清理并重新构建您的项目。

此外,请确保控制器中的所有方法都具有 ActionVerbs,例如:HttpGet、HttpPost等,除了带有[ApiExplorerSettings(IgnoreApi = true)]属性的方法。

ActionVerb 和 Route 必须分开写: 应该使用 [HttpGet,Route("getuser")] 而不是 [HttpGet("getuser")]


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