如何使用Swagger生成Options(CORS) [英] How to generate Options(CORS) with Swagger

查看:291
本文介绍了如何使用Swagger生成Options(CORS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个我们正在研究的项目,我们正在自动生成一个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定义文件中自动生成该文件吗?或我们该怎么做,Amazon API网关需要这样做(文档:

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)

推荐答案

您可以通过

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生成Options(CORS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆