我是Swagger的新手,并在我的桌面上使用本地运行的Swagger Editor来测试API。我不负责服务器配置,也无权进行更改。我已设置安全定义并且我的授权正常。现在我正在尝试设置我的第一个路径模式,但是当我执行它时,我收到一条错误消息,上面写着“TypeError:Failed to fetch”,并且Response Headers字段为空。
但是,当我复制Swagger编辑器提供的Curl请求并在GitBash中运行它时,它返回我期望的值。所以我知道Swagger Editor已经创建了一个工作请求。
我知道我的安全授权正在运行,因为我可以看到它在Curl请求中返回的令牌。
身份验证架构和路径架构都命中了不同的子域。身份验证由betaauthorize.myDomain.com处理,而路径由betaapi.myDoamin.com处理。
我再次从桌面硬盘驱动器运行Swagger Editor。是否存在某种我错过的Swagger Editor配置设置?我需要让服务器管理员知道的服务器配置问题吗?我一直在努力解决这个问题两天,我完全没有想法。任何建议,将不胜感激。
事实证明,我的代码需要所有请求的授权密钥,包括OPTIONS请求。经过一些研究和咨询后,我确定最佳做法是在没有任何授权的情况下回应OPTIONS请求 - 后续请求需要授权。一旦我修改了代码以便在没有OPTIONS请求授权的情况下继续进行,我就能够让Swagger为我的项目工作。
通常,当您使用错误的HTTP / HTTPS方案时会出现此错误。在您的招摇页面上,有一个方案下拉列表。如果您正在运行http,请确保未选择https。 Https是默认值。
那条消息正在吃掉实际的错误。问题是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个不同命名空间的Class'Tomething'具有相同的模式,因此Swagger会因为它们相同而窒息。解决这个问题的一个方法是配置Swagger以完全限定Schema ID,因此DoSomething()方法中的Something和DoSomethingElse()方法中的Something将在生成.json文件时被Swagger识别为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);
});
}
我遇到了同样的问题。当swagger-editor托管在与API不同的域上时,就会出现问题。
您将不得不更改它或设置适当的CORS标头。