Ocelot 跨域配置

这里扩展了一个 Ocelot pipeline 的配置,这样我们可以直接很方便的直接在 Startup 里配置 Ocelot 的请求管道。

在 HttpRequester 中间件后面添加这个中间件在响应中增加跨域请求头配置,这里先判断了一下下面的api有没有配置,如果已经配置则不再配置,使用下游api的跨域配置,这样一来,只需要在网关配置指定的允许跨域访问的源即使下游api没有设置跨域也是可以访问了

需要说明一下的是如果想要这样配置需要 Ocelot 13.2.0 以上的包,因为之前 HttpRequester 这个中间件没有调用下一个中间件,详见 https://github.com/ThreeMammals/Ocelot/pull/830

app.UseOcelot((ocelotBuilder, pipelineConfiguration) =>
                {
                    // This is registered to catch any global exceptions that are not handled
                    // It also sets the Request Id if anything is set globally
                    ocelotBuilder.UseExceptionHandlerMiddleware();
                    // Allow the user to respond with absolutely anything they want.
                    if (pipelineConfiguration.PreErrorResponderMiddleware != null)
                    {
                        ocelotBuilder.Use(pipelineConfiguration.PreErrorResponderMiddleware);
                    }
                    // This is registered first so it can catch any errors and issue an appropriate response
                    ocelotBuilder.UseResponderMiddleware();
                    ocelotBuilder.UseDownstreamRouteFinderMiddleware();
                    ocelotBuilder.UseDownstreamRequestInitialiser();
                    ocelotBuilder.UseRequestIdMiddleware();
                    ocelotBuilder.UseMiddleware<ClaimsToHeadersMiddleware>();
                    ocelotBuilder.UseLoadBalancingMiddleware();
                    ocelotBuilder.UseDownstreamUrlCreatorMiddleware();
                    ocelotBuilder.UseOutputCacheMiddleware();
                    ocelotBuilder.UseMiddleware<HttpRequesterMiddleware>();
                    // cors headers
                    ocelotBuilder.Use(async (context, next) =>
                    {
                        if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowOrigin))
                        {
                            var allowedOrigins = Configuration.GetAppSetting("AllowedOrigins").SplitArray<string>();
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowOrigin, allowedOrigins.Length == 0 ? new[] { "*" } : allowedOrigins));
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowHeaders, new[] { "*" }));
                            context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlRequestMethod, new[] { "*" }));
                        }
                        await next();
                    });
                })
                .Wait();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值