该消息正在吞噬实际错误。
问题要么是 API 配置错误,例如 CORS 不允许返回 json 文件,要么是 Swagger 配置本身。
这里有一些可以尝试的方法。
随着 Swagger 的运行和浏览器中的消息
直接浏览到 JSON url 本身(例如:http://myserver.domain:port/swagger/v1/swagger.json)。如果您收到 404 错误,
SwaggerEndpoint 值不正确。
SwaggerEndpoint("incorrect/v1/swagger.json", "My incorrect Application Version 1");
SwaggerEndpoint("v1/swagger.json", "My correct Application Version 1");
一旦您尝试从正确的路径检索 swagger.json 文件,您将在浏览器中看到 JSON,或者 Swagger 方法调用出现异常。您可以从 Swagger 中查看堆栈跟踪以确定原因。
发生这种情况的一个原因是因为控制器中有一个不是 API 端点的公共方法,但 Swagger 认为它是,直到它无法读取 HTTPAttribute 以确定端点正在使用的动词(即: GET、POST ...) 或路由 (/controller/action/{parameter:dataType}/somethingElse)
// This should be private, not public!
public ReturnType MyHelperMethod(object parameter){
//Do something to parameter
return InstanceOfReturnType;
}
另一个原因是,如果使用的不同数据模型不是唯一的架构,并且您没有配置 swagger 来完全限定架构模型以保证唯一性。
示例:-
[HttpGet, Route("something", Name = "Do Something")]
public IActionResult DoSomething([FromBody] Datamodel.Something something)
{
var returnValue = Service.DoSomething(something);
return returnValue;
}
[HttpGet, Route("somethingElse", Name = "Do Something Else")]
public IActionResult DoSomethingElse([FromBody] IdenticalDatamodel.Something somethingElse)
{
var returnValue = Service.DoSomethingElse(somethingElse);
return returnValue;
}
namespace IdenticalDatamodel {
public class Something {
public string SomeProperty{ get; set;}
}
}
namespace Datamodel {
public class Something {
public string SomeProperty{ get; set;}
}
}
在这种情况下,来自 2 个不同命名空间的类“Something”具有相同的架构,因此 Swagger 窒息,因为它们是相同的。对此的一种解决方法是将 Swagger 配置为完全限定 Schema Id,因此 DoSomething() 方法中的 Something 和 DoSomethingElse() 方法中的 Something 将被标识为 Datamodel.Something 和 IdenticalDatamodel.Something
为此,您可以在 Startup.cs 中使用以下代码
public void ConfigureServices(IServiceCollection services)
{
//Add a bunch of service configurations here
// ...
// It's probably better to externalize the Swagger config to it's own private helper method
services.AddSwaggerGen(swagger =>
{
// Setup your Swagger doc, security etc here
});
// Customize the Swagger generator here
services.ConfigureSwaggerGen(options =>
{
// Use fully qualified schema object names to ensure uniqueness
options.CustomSchemaIds(configuration => configuration.FullName);
});
}