问题描述
对于我们正在进行的项目,我们会自动生成一个 Swagger 文件.然而,此时我们正在努力解决 CORS 部分.
For a project we are working on we are generating an Swagger File automatically. However at this moment we are struggling with the CORS part.
我们正在使用 Amazon API 网关导入 api 功能.要将其与 Swagger 和 CORS 结合使用,我们必须在源代码中创建一个附加操作(操作),它允许每个 api 方法(操作)使用 CORS(选项)!例如:
We are using the Amazon API gateway import api functionality. To use this in combination with Swagger and CORS, we have to create an additional action (operation) in our source code which allows CORS(options) for each api method (operation)! eg:
[HttpOptions]
[Route("{id}")]
[ProducesResponseType((int)HttpStatusCode.OK)]
public IActionResult UserOptions()
{
return new OkResult();
}
如您所见,这会使代码变得更脏.这是一个临时修复,但我们找不到其他方法.有没有办法在 swagger 定义文件中自动生成它?或者我们怎么能做到这一点,亚马逊 API 网关需要这个(文档:http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html)
As you can see this makes the code a lot dirtier. this is a temporary fix, but we can not find another way. Is there any way to generate this in the swagger definition file automatically? Or how can we do this, Amazon API gateway required this (documentation: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html)
推荐答案
可以通过x-amazon-apigateway-integration swagger 扩展.
You can drive api gateway through x-amazon-apigateway-integration swagger extension.
使用 Swashbuckle 文档过滤器,您可以在所有路径上生成选项操作,而无需在控制器中执行相应操作.
Using Swashbuckle document filter, you can generate a option operation on all your paths without corresponding action in your controller.
这是一个示例代码,它将为您的 swagger 中的所有路径生成一个选项操作,并添加使用 swagger 扩展以在这些 OPTION 方法上在 api 网关中生成一个模拟:
Here is a sample code that will generate an option operation for all paths in your swagger and add use swagger extensions to generate a mock in api gateway on these OPTION methods:
public class AddCorsApiGatewayDocumentFilter : IDocumentFilter
{
private Operation BuildCorsOptionOperation()
{
var response = new Response
{
Description = "Successful operation",
Headers = new Dictionary<string, Header>
{
{ "Access-Control-Allow-Origin", new Header(){Type="string",Description="URI that may access the resource" } },
{ "Access-Control-Allow-Methods", new Header(){Type="string",Description="Method or methods allowed when accessing the resource" } },
{ "Access-Control-Allow-Headers", new Header(){Type="string",Description="Used in response to a preflight request to indicate which HTTP headers can be used when making the request." } },
}
};
return new Operation
{
Consumes = new List<string> { "application/json" },
Produces = new List<string> { "application/json" },
Responses = new Dictionary<string, Response>{{"200",response}}
};
}
private object BuildApiGatewayIntegrationExtension()
{
return new
{
responses = new
{
@default = new
{
statusCode = "200",
responseParameters = new Dictionary<string, string>
{
{ "method.response.header.Access-Control-Allow-Methods", "'POST,GET,OPTIONS'" },
{ "method.response.header.Access-Control-Allow-Headers", "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"},
{ "method.response.header.Access-Control-Allow-Origin", "'*'"}
}
},
},
passthroughBehavior = "when_no_match",
requestTemplates = new Dictionary<string, string> { { "application/json", "{"statusCode": 200}" } },
type = "mock"
};
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
foreach (var path in swaggerDoc.Paths)
{
var corsOptionOperation = BuildCorsOptionOperation();
var awsApiGatewayExtension = BuildApiGatewayIntegrationExtension();
corsOptionOperation.Extensions.Add("x-amazon-apigateway-integration", awsApiGatewayExtension);
path.Value.Options = corsOptionOperation;
}
}
}
不要忘记在 swashbuckle 中注册该过滤器:
Do not forget to register that filter in swashbuckle:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
c.DocumentFilter<AddCorsApiGatewayDocumentFilter>();
});
}
这篇关于如何使用 Swagger 生成选项(CORS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!