public HeaderTransformations Create(FileReRoute fileReRoute)
        {
            var upstream             = new List <HeaderFindAndReplace>();
            var addHeadersToUpstream = new List <AddHeader>();

            foreach (var input in fileReRoute.UpstreamHeaderTransform)
            {
                if (input.Value.Contains(","))
                {
                    var hAndr = Map(input);
                    if (!hAndr.IsError)
                    {
                        upstream.Add(hAndr.Data);
                    }
                    else
                    {
                        _logger.LogWarning($"Unable to add UpstreamHeaderTransform {input.Key}: {input.Value}");
                    }
                }
                else
                {
                    addHeadersToUpstream.Add(new AddHeader(input.Key, input.Value));
                }
            }

            var downstream             = new List <HeaderFindAndReplace>();
            var addHeadersToDownstream = new List <AddHeader>();

            foreach (var input in fileReRoute.DownstreamHeaderTransform)
            {
                if (input.Value.Contains(","))
                {
                    var hAndr = Map(input);
                    if (!hAndr.IsError)
                    {
                        downstream.Add(hAndr.Data);
                    }
                    else
                    {
                        _logger.LogWarning($"Unable to add DownstreamHeaderTransform {input.Key}: {input.Value}");
                    }
                }
                else
                {
                    addHeadersToDownstream.Add(new AddHeader(input.Key, input.Value));
                }
            }

            return(new HeaderTransformations(upstream, downstream, addHeadersToDownstream, addHeadersToUpstream));
        }
Esempio n. 2
0
        public async Task <List <Service> > Get()
        {
            var queryResult = await _consul.Health.Service(_config.KeyOfServiceInConsul, string.Empty, false);

            var services = new List <Service>();

            foreach (var serviceEntry in queryResult.Response)
            {
                if (IsValid(serviceEntry))
                {
                    var nodes = await _consul.Catalog.Nodes();

                    if (nodes.Response == null)
                    {
                        services.Add(BuildService(serviceEntry, null));
                    }
                    else
                    {
                        var serviceNode = nodes.Response.FirstOrDefault(n => n.Address == serviceEntry.Service.Address);
                        services.Add(BuildService(serviceEntry, serviceNode));
                    }
                }
                else
                {
                    _logger.LogWarning($"Unable to use service Address: {serviceEntry.Service.Address} and Port: {serviceEntry.Service.Port} as it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
                }
            }

            return(services.ToList());
        }
        private async Task Poll()
        {
            _logger.LogInformation("Started polling");

            var fileConfig = await _repo.Get();

            if (fileConfig.IsError)
            {
                _logger.LogWarning($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}");
                return;
            }

            var asJson = ToJson(fileConfig.Data);

            if (!fileConfig.IsError && asJson != _previousAsJson)
            {
                var config = await _internalConfigCreator.Create(fileConfig.Data);

                if (!config.IsError)
                {
                    _internalConfigRepo.AddOrReplace(config.Data);
                }

                _previousAsJson = asJson;
            }

            _logger.LogInformation("Finished polling");
        }
Esempio n. 4
0
        public void Add(List <AddHeader> addHeaders, DownstreamResponse response)
        {
            foreach (var add in addHeaders)
            {
                if (add.Value.StartsWith('{') && add.Value.EndsWith('}'))
                {
                    var value = _placeholders.Get(add.Value);

                    if (value.IsError)
                    {
                        _logger.LogWarning($"Unable to add header to response {add.Key}: {add.Value}");
                        continue;
                    }

                    response.Headers.Add(new Header(add.Key, new List <string> {
                        value.Data
                    }));
                }
                else
                {
                    response.Headers.Add(new Header(add.Key, new List <string> {
                        add.Value
                    }));
                }
            }
        }
Esempio n. 5
0
        public void SetHeadersOnDownstreamRequest(IEnumerable <AddHeader> headers, HttpContext context)
        {
            var requestHeader = context.Request.Headers;

            foreach (var header in headers)
            {
                if (requestHeader.ContainsKey(header.Key))
                {
                    requestHeader.Remove(header.Key);
                }

                if (header.Value.StartsWith("{") && header.Value.EndsWith("}"))
                {
                    var value = _placeholders.Get(header.Value);

                    if (value.IsError)
                    {
                        _logger.LogWarning($"Unable to add header to response {header.Key}: {header.Value}");
                        continue;
                    }

                    requestHeader.Add(header.Key, new StringValues(value.Data));
                }
                else
                {
                    requestHeader.Add(header.Key, header.Value);
                }
            }
        }
        public IHttpClient Create(DownstreamContext context)
        {
            _cacheKey = GetCacheKey(context);

            var httpClient = _cacheHandlers.Get(_cacheKey);

            if (httpClient != null)
            {
                _client = httpClient;
                return(httpClient);
            }

            var handler = CreateHandler(context);

            if (context.DownstreamReRoute.DangerousAcceptAnyServerCertificateValidator)
            {
                handler.ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => true;

                _logger
                .LogWarning($"You have ignored all SSL warnings by using DangerousAcceptAnyServerCertificateValidator for this DownstreamReRoute, UpstreamPathTemplate: {context.DownstreamReRoute.UpstreamPathTemplate}, DownstreamPathTemplate: {context.DownstreamReRoute.DownstreamPathTemplate}");
            }

            var timeout = context.DownstreamReRoute.QosOptions.TimeoutValue == 0
                ? _defaultTimeout
                : TimeSpan.FromMilliseconds(context.DownstreamReRoute.QosOptions.TimeoutValue);

            _httpClient = new HttpClient(CreateHttpMessageHandler(handler, context.DownstreamReRoute))
            {
                Timeout = timeout
            };

            _client = new HttpClientWrapper(_httpClient);

            return(_client);
        }
Esempio n. 7
0
        public async Task <List <Service> > Get()
        {
            // Services/srvname/srvid
            var queryResult = await _zookeeperClient.GetRangeAsync($"/Ocelot/Services/{_config.KeyOfServiceInZookeeper}");

            var services = new List <Service>();

            foreach (var dic in queryResult)
            {
                var srvs = dic.Key.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (srvs.Length == 4)
                {
                    var serviceEntry = JsonConvert.DeserializeObject <ServiceEntry>(dic.Value);
                    serviceEntry.Name = srvs[2];
                    serviceEntry.Id   = srvs[3];
                    if (IsValid(serviceEntry))
                    {
                        services.Add(BuildService(serviceEntry));
                    }
                    else
                    {
                        _logger.LogWarning($"Unable to use service Address: {serviceEntry.Host} and Port: {serviceEntry.Port} as it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
                    }
                }
            }

            return(services.ToList());
        }
        private List <Service> GetServices()
        {
            if (!_cache.TryGetValue(GetKey(), out Service service))
            {
                service = GetServiceInner();

                if (service != null)
                {
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                                            .SetAbsoluteExpiration(GetExpiration());
                    _cache.Set(GetKey(), service, cacheEntryOptions);
                }
                else
                {
                    _logger.LogWarning(
                        $"Unable to use service '{_serviceName}' as it is invalid. Service is missing in configuration");
                    return(new List <Service>());
                }
            }

            return(new List <Service>()
            {
                service
            });
        }
Esempio n. 9
0
        public Response <List <Func <DelegatingHandler> > > Get(DownstreamReRoute downstreamReRoute)
        {
            var globalDelegatingHandlers = _serviceProvider
                                           .GetServices <GlobalDelegatingHandler>()
                                           .ToList();

            var reRouteSpecificHandlers = _serviceProvider
                                          .GetServices <DelegatingHandler>()
                                          .ToList();

            var handlers = new List <Func <DelegatingHandler> >();

            foreach (var handler in globalDelegatingHandlers)
            {
                if (GlobalIsInHandlersConfig(downstreamReRoute, handler))
                {
                    reRouteSpecificHandlers.Add(handler.DelegatingHandler);
                }
                else
                {
                    handlers.Add(() => handler.DelegatingHandler);
                }
            }

            if (downstreamReRoute.DelegatingHandlers.Any())
            {
                var sorted = SortByConfigOrder(downstreamReRoute, reRouteSpecificHandlers);

                foreach (var handler in sorted)
                {
                    handlers.Add(() => handler);
                }
            }

            if (downstreamReRoute.HttpHandlerOptions.UseTracing)
            {
                handlers.Add(() => (DelegatingHandler)_tracingFactory.Get());
            }

            if (downstreamReRoute.QosOptions.UseQos)
            {
                var handler = _qoSFactory.Get(downstreamReRoute);

                if (handler != null && !handler.IsError)
                {
                    handlers.Add(() => handler.Data);
                }
                else
                {
                    _logger.LogWarning($"ReRoute {downstreamReRoute.UpstreamPathTemplate} specifies use QoS but no QosHandler found in DI container. Will use not use a QosHandler, please check your setup!");
                    handlers.Add(() => new NoQosDelegatingHandler());
                }
            }

            return(new OkResponse <List <Func <DelegatingHandler> > >(handlers));
        }
Esempio n. 10
0
        public async Task <List <Service> > Get()
        {
            // 如果Consul有问题会导致网关异常
            //var queryResult = await _consul.Health.Service(_config.KeyOfServiceInConsul, string.Empty, true);
            if (_config.KeyOfServiceInConsul == string.Empty)
            {
                return(new List <Service>());
            }
            QueryResult <ServiceEntry[]> queryResult = new QueryResult <ServiceEntry[]>();

            try
            {
                queryResult = await _consul.Health.Service(_config.KeyOfServiceInConsul, string.Empty, true);
            }
            catch (Exception ex)
            {
                _logger.LogError($"_consul.Health.Service异常{_config.KeyOfServiceInConsul}", ex);
                return(await GetServiceFromCache(_config.KeyOfServiceInConsul));
            }

            var services = new List <Service>();

            foreach (var serviceEntry in queryResult.Response)
            {
                if (IsValid(serviceEntry))
                {
                    try
                    {
                        var nodes = await _consul.Catalog.Nodes();

                        if (nodes.Response == null)
                        {
                            services.Add(BuildService(serviceEntry, null));
                        }
                        else
                        {
                            var serviceNode = nodes.Response.FirstOrDefault(n => n.Address == serviceEntry.Service.Address);
                            services.Add(BuildService(serviceEntry, serviceNode));
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"_consul.Catalog.Nodes异常{serviceEntry.Service}", ex);
                        return(await GetServiceFromCache(_config.KeyOfServiceInConsul));
                    }
                }
                else
                {
                    _logger.LogWarning($"Unable to use service Address: {serviceEntry.Service.Address} and Port: {serviceEntry.Service.Port} as it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
                }
            }

            await ServiceToCache(_config.KeyOfServiceInConsul, services);

            return(services.ToList());
        }
Esempio n. 11
0
        public IHttpClient Create(DownstreamContext context)
        {
            _cacheKey = GetCacheKey(context);

            var httpClient = _cacheHandlers.Get(_cacheKey);

            if (httpClient != null)
            {
                return(httpClient);
            }
            bool useCookies = context.DownstreamReRoute.HttpHandlerOptions.UseCookieContainer;
            HttpClientHandler httpclientHandler;

            // Dont' create the CookieContainer if UseCookies is not set ot the HttpClient will complain
            // under .Net Full Framework
            if (useCookies)
            {
                httpclientHandler = new HttpClientHandler
                {
                    AllowAutoRedirect = context.DownstreamReRoute.HttpHandlerOptions.AllowAutoRedirect,
                    UseCookies        = context.DownstreamReRoute.HttpHandlerOptions.UseCookieContainer,
                    CookieContainer   = new CookieContainer()
                };
            }
            else
            {
                httpclientHandler = new HttpClientHandler
                {
                    AllowAutoRedirect = context.DownstreamReRoute.HttpHandlerOptions.AllowAutoRedirect,
                    UseCookies        = context.DownstreamReRoute.HttpHandlerOptions.UseCookieContainer,
                };
            }

            if (context.DownstreamReRoute.DangerousAcceptAnyServerCertificateValidator)
            {
                httpclientHandler.ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => true;

                _logger
                .LogWarning($"You have ignored all SSL warnings by using DangerousAcceptAnyServerCertificateValidator for this DownstreamReRoute, UpstreamPathTemplate: {context.DownstreamReRoute.UpstreamPathTemplate}, DownstreamPathTemplate: {context.DownstreamReRoute.DownstreamPathTemplate}");
            }

            var timeout = context.DownstreamReRoute.QosOptions.TimeoutValue == 0
                ? _defaultTimeout
                : TimeSpan.FromMilliseconds(context.DownstreamReRoute.QosOptions.TimeoutValue);

            _httpClient = new HttpClient(CreateHttpMessageHandler(httpclientHandler, context.DownstreamReRoute))
            {
                Timeout = timeout
            };

            _client = new HttpClientWrapper(_httpClient);

            return(_client);
        }
Esempio n. 12
0
        /// <summary>
        /// 添加服务
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        private void Add(string key, string value)
        {
            var srvs         = key.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var serviceEntry = JsonConvert.DeserializeObject <ServiceEntry>(value);

            serviceEntry.Name = srvs[2];
            serviceEntry.Id   = srvs[3];
            if (this.IsValid(serviceEntry))
            {
                Services.Add(BuildService(serviceEntry));
            }
            else
            {
                logger.LogWarning($"Unable to use service Address: {serviceEntry.Host} and Port: {serviceEntry.Port} as it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
            }
        }
Esempio n. 13
0
        public async Task <List <Service> > Get()
        {
            var service = await kubeApi.ServicesV1().Get(kubeRegistryConfiguration.KeyOfServiceInK8s, kubeRegistryConfiguration.KubeNamespace);

            var services = new List <Service>();

            if (IsValid(service))
            {
                services.Add(BuildService(service));
            }
            else
            {
                logger.LogWarning($"namespace:{kubeRegistryConfiguration.KubeNamespace }service:{kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
            }
            return(services);
        }
Esempio n. 14
0
        public async Task <List <Service> > Get()
        {
            var endpoint = await _kubeApi
                           .ResourceClient(client => new EndPointClientV1(client))
                           .Get(_kubeRegistryConfiguration.KeyOfServiceInK8s, _kubeRegistryConfiguration.KubeNamespace);

            var services = new List <Service>();

            if (endpoint != null && endpoint.Subsets.Any())
            {
                services.AddRange(BuildServices(endpoint));
            }
            else
            {
                _logger.LogWarning($"namespace:{_kubeRegistryConfiguration.KubeNamespace }service:{_kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
            }
            return(services);
        }
        private async Task Poll()
        {
            var fileConfig = await _repo.Get();

            if (fileConfig.IsError)
            {
                _logger.LogWarning($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}");
                return;
            }
            else
            {
                var config = await _internalConfigCreator.Create(fileConfig.Data);

                if (!config.IsError)
                {
                    _internalConfigRepo.AddOrReplace(config.Data);
                }
            }
        }
Esempio n. 16
0
        public async Task <List <Service> > Get()
        {
            var queryResult = await _consul.Health.Service(_config.KeyOfServiceInConsul, string.Empty, true);

            var services = new List <Service>();

            foreach (var serviceEntry in queryResult.Response)
            {
                if (IsValid(serviceEntry))
                {
                    services.Add(BuildService(serviceEntry));
                }
                else
                {
                    _logger.LogWarning($"Unable to use service Address: {serviceEntry.Service.Address} and Port: {serviceEntry.Service.Port} as it is invalid. Address must contain host only e.g. localhost and port must be greater than 0");
                }
            }

            return(services.ToList());
        }
Esempio n. 17
0
        public IHttpClient Create(DownstreamContext context)
        {
            _cacheKey = GetCacheKey(context);

            var httpClient = _cacheHandlers.Get(_cacheKey);

            if (httpClient != null)
            {
                return(httpClient);
            }

            var httpclientHandler = new HttpClientHandler
            {
                AllowAutoRedirect = context.DownstreamReRoute.HttpHandlerOptions.AllowAutoRedirect,
                UseCookies        = context.DownstreamReRoute.HttpHandlerOptions.UseCookieContainer,
                CookieContainer   = new CookieContainer()
            };

            if (context.DownstreamReRoute.DangerousAcceptAnyServerCertificateValidator)
            {
                httpclientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

                _logger
                .LogWarning($"You have ignored all SSL warnings by using DangerousAcceptAnyServerCertificateValidator for this DownstreamReRoute, UpstreamPathTemplate: {context.DownstreamReRoute.UpstreamPathTemplate}, DownstreamPathTemplate: {context.DownstreamReRoute.DownstreamPathTemplate}");
            }

            var timeout = context.DownstreamReRoute.QosOptionsOptions.TimeoutValue == 0
                ? _defaultTimeout
                : TimeSpan.FromMilliseconds(context.DownstreamReRoute.QosOptionsOptions.TimeoutValue);

            _httpClient = new HttpClient(CreateHttpMessageHandler(httpclientHandler, context.DownstreamReRoute))
            {
                Timeout = timeout
            };

            _client = new HttpClientWrapper(_httpClient);

            return(_client);
        }
Esempio n. 18
0
        public void Add(List <AddHeader> addHeaders, HttpResponseMessage response)
        {
            foreach (var add in addHeaders)
            {
                if (add.Value.StartsWith('{') && add.Value.EndsWith('}'))
                {
                    var value = _placeholders.Get(add.Value);

                    if (value.IsError)
                    {
                        _logger.LogWarning($"Unable to add header to response {add.Key}: {add.Value}");
                        continue;
                    }

                    response.Headers.TryAddWithoutValidation(add.Key, value.Data);
                }
                else
                {
                    response.Headers.TryAddWithoutValidation(add.Key, add.Value);
                }
            }
        }
        private async Task Poll()
        {
            _logger.LogInformation("Started polling consul");

            var fileConfig = await _repo.Get();

            if (fileConfig.IsError)
            {
                _logger.LogWarning($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}");
                return;
            }

            var asJson = ToJson(fileConfig.Data);

            if (!fileConfig.IsError && asJson != _previousAsJson)
            {
                await _setter.Set(fileConfig.Data);

                _previousAsJson = asJson;
            }

            _logger.LogInformation("Finished polling consul");
        }
Esempio n. 20
0
        public async Task <FileConfiguration> GetFileConfiguration(string name)
        {
            var file = new FileConfiguration();

            // 提取全局配置信息
            var globalResult = await _ocelotGlobalConfigurationRepository.FindByNameAsync(name);

            if (globalResult != null)
            {
                var fileGlobalConfig = new FileGlobalConfiguration
                {
                    BaseUrl          = globalResult.BaseUrl,
                    DownstreamScheme = globalResult.DownstreamScheme,
                    RequestIdKey     = globalResult.RequestIdKey
                };

                if (globalResult.HttpHandlerOption != null)
                {
                    var httpHandlerOption = globalResult.HttpHandlerOption;
                    fileGlobalConfig.HttpHandlerOptions = new FileHttpHandlerOptions
                    {
                        AllowAutoRedirect       = httpHandlerOption.AllowAutoRedirect,
                        UseCookieContainer      = httpHandlerOption.UseCookieContainer,
                        UseProxy                = httpHandlerOption.UseProxy,
                        UseTracing              = httpHandlerOption.UseTracing,
                        MaxConnectionsPerServer = httpHandlerOption.MaxConnectionsPerServer
                    };
                }
                if (globalResult.LoadBalancerOption != null)
                {
                    var loadBalancerOption = globalResult.LoadBalancerOption;
                    fileGlobalConfig.LoadBalancerOptions = new FileLoadBalancerOptions
                    {
                        Expiry = loadBalancerOption.Expiry,
                        Key    = loadBalancerOption.Key,
                        Type   = loadBalancerOption.Type
                    };
                }
                if (globalResult.QoSOption != null)
                {
                    var qoSOption = globalResult.QoSOption;
                    fileGlobalConfig.QoSOptions = new FileQoSOptions
                    {
                        ExceptionsAllowedBeforeBreaking = qoSOption.ExceptionsAllowedBeforeBreaking,
                        DurationOfBreak = qoSOption.DurationOfBreak,
                        TimeoutValue    = qoSOption.TimeoutValue
                    };
                }
                if (globalResult.ServiceDiscoveryProvider != null)
                {
                    var serviceDiscoveryProvider = globalResult.ServiceDiscoveryProvider;
                    fileGlobalConfig.ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
                    {
                        ConfigurationKey = serviceDiscoveryProvider.ConfigurationKey,
                        Host             = serviceDiscoveryProvider.Host,
                        Namespace        = serviceDiscoveryProvider.Namespace,
                        PollingInterval  = serviceDiscoveryProvider.PollingInterval,
                        Port             = serviceDiscoveryProvider.Port,
                        Token            = serviceDiscoveryProvider.Token,
                        Type             = serviceDiscoveryProvider.Type
                    };
                }
                if (globalResult.RateLimitOption != null)
                {
                    var rateLimitOption = globalResult.RateLimitOption;
                    fileGlobalConfig.RateLimitOptions = new FileRateLimitOptions
                    {
                        ClientIdHeader          = rateLimitOption.ClientIdHeader,
                        DisableRateLimitHeaders = rateLimitOption.DisableRateLimitHeaders,
                        HttpStatusCode          = rateLimitOption.HttpStatusCode,
                        QuotaExceededMessage    = rateLimitOption.QuotaExceededMessage,
                        RateLimitCounterPrefix  = rateLimitOption.RateLimitCounterPrefix
                    };
                }

                file.GlobalConfiguration = fileGlobalConfig;
                //TODO: Optimize code structure
                if (globalResult?.Routes?.Count > 0)
                {
                    _logger.LogInformation($"Route Count:{ globalResult?.Routes?.Count }");
                    //提取路由信息
                    var Routes = globalResult.Routes.OrderBy(c => c.Sort);

                    List <FileRoute> fileRoutes = new List <FileRoute>();
                    foreach (var route in Routes)
                    {
                        _logger.LogInformation($"Loading Route: {route.Name}");
                        var r = new FileRoute
                        {
                            Key                    = route.Key,
                            Priority               = route.Priority,
                            ServiceName            = route.ServiceName,
                            Timeout                = route.Timeout,
                            DownstreamPathTemplate = route.DownstreamPathTemplate,
                            DownstreamScheme       = route.DownstreamScheme,
                            UpstreamHost           = route.UpstreamHost,
                            DangerousAcceptAnyServerCertificateValidator = route.DangerousAcceptAnyServerCertificateValidator,
                            DownstreamHttpMethod         = route.DownstreamHttpMethod,
                            RequestIdKey                 = route.RequestIdKey,
                            UpstreamPathTemplate         = route.UpstreamPathTemplate,
                            ServiceNamespace             = route.ServiceNamespace,
                            RouteIsCaseSensitive         = route.RouteIsCaseSensitive,
                            AddClaimsToRequest           = route.AddClaimsToRequests,
                            AddHeadersToRequest          = route.AddHeadersToRequests,
                            AddQueriesToRequest          = route.AddQueriesToRequests,
                            ChangeDownstreamPathTemplate = route.ChangeDownstreamPathTemplates,
                            DownstreamHeaderTransform    = route.DownstreamHeaderTransforms,
                            RouteClaimsRequirement       = route.RouteClaimsRequirements,
                            UpstreamHeaderTransform      = route.UpstreamHeaderTransforms,
                            // AuthenticationOptions = null,
                            // DelegatingHandlers = null,
                            // DownstreamHostAndPorts = null,
                            // FileCacheOptions = null,
                            // HttpHandlerOptions = null,
                            // LoadBalancerOptions = null,
                            // QoSOptions = null,
                            // RateLimitOptions = null,
                            // SecurityOptions = null,
                            // UpstreamHttpMethod = null
                        };
                        if (route.AuthenticationOption != null)
                        {
                            var authenticationOption = route.AuthenticationOption;
                            r.AuthenticationOptions = new FileAuthenticationOptions
                            {
                                AuthenticationProviderKey = authenticationOption.AuthenticationProviderKey,
                                AllowedScopes             = authenticationOption.AllowedScopes.Select(c => c.Scope).ToList()
                            };
                        }
                        if (route.DelegatingHandlers != null && route.DelegatingHandlers.Count > 0)
                        {
                            r.DelegatingHandlers = route.DelegatingHandlers.Select(c => c.Delegating).ToList();
                        }
                        if (route.DownstreamHostAndPorts != null && route.DownstreamHostAndPorts.Count > 0)
                        {
                            var downstreamHostAndPorts = new List <FileHostAndPort>();
                            foreach (var host in route.DownstreamHostAndPorts)
                            {
                                downstreamHostAndPorts.Add(new FileHostAndPort
                                {
                                    Host = host.Host,
                                    Port = host.Port
                                });
                            }
                            r.DownstreamHostAndPorts = downstreamHostAndPorts;
                        }
                        if (route.CacheOption != null)
                        {
                            var cacheOption = route.CacheOption;
                            r.FileCacheOptions = new FileCacheOptions
                            {
                                TtlSeconds = cacheOption.TtlSeconds,
                                Region     = cacheOption.Region
                            };
                        }
                        if (route.HttpHandlerOption != null)
                        {
                            var httpHandlerOption = route.HttpHandlerOption;
                            r.HttpHandlerOptions = new FileHttpHandlerOptions
                            {
                                AllowAutoRedirect       = httpHandlerOption.AllowAutoRedirect,
                                UseCookieContainer      = httpHandlerOption.UseCookieContainer,
                                UseProxy                = httpHandlerOption.UseProxy,
                                UseTracing              = httpHandlerOption.UseTracing,
                                MaxConnectionsPerServer = httpHandlerOption.MaxConnectionsPerServer
                            };
                        }
                        if (route.LoadBalancerOption != null)
                        {
                            var loadBalancerOptions = route.LoadBalancerOption;
                            r.LoadBalancerOptions = new FileLoadBalancerOptions
                            {
                                Expiry = loadBalancerOptions.Expiry,
                                Key    = loadBalancerOptions.Key,
                                Type   = loadBalancerOptions.Type
                            };
                        }
                        if (route.QoSOption != null)
                        {
                            var qoSOption = route.QoSOption;
                            r.QoSOptions = new FileQoSOptions
                            {
                                ExceptionsAllowedBeforeBreaking = qoSOption.ExceptionsAllowedBeforeBreaking,
                                DurationOfBreak = qoSOption.DurationOfBreak,
                                TimeoutValue    = qoSOption.TimeoutValue
                            };
                        }
                        if (route.RateLimitOption != null)
                        {
                            var rateLimitOption = route.RateLimitOption;
                            r.RateLimitOptions = new FileRateLimitRule
                            {
                                ClientWhitelist    = rateLimitOption.ClientWhitelist.Select(c => c.Whitelist).ToList(),
                                EnableRateLimiting = rateLimitOption.EnableRateLimiting,
                                Limit          = rateLimitOption.Limit,
                                Period         = rateLimitOption.Period,
                                PeriodTimespan = rateLimitOption.PeriodTimespan
                            };
                        }
                        if (route.SecurityOption != null)
                        {
                            var securityOption = route.SecurityOption;
                            r.SecurityOptions = new FileSecurityOptions
                            {
                                IPAllowedList = securityOption.IPAllowedList.Select(c => c.IP).ToList(),
                                IPBlockedList = securityOption.IPBlockedList.Select(c => c.IP).ToList()
                            };
                        }

                        if (route.UpstreamHttpMethods != null)
                        {
                            r.UpstreamHttpMethod = route.UpstreamHttpMethods.Select(c => c.Method).ToList();
                        }
                        r.UpstreamPathTemplate = route.UpstreamPathTemplate;

                        file.Routes.Add(r);
                    }
                }
                else
                {
                    _logger.LogWarning($"Not Found Route");
                }
            }
            else
            {
                throw new Exception(string.Format("Not found '{0}' gateway name config", name));
            }
            return(file);
        }
        public async Task Invoke(DownstreamContext context)
        {
            var routeResponse = this._routeValuesBuilder.Build(context);

            if (routeResponse.IsError)
            {
                Logger.LogDebug("IRouteValuesBuilder Parsing Route Values errors");
                SetPipelineError(context, routeResponse.Errors);
                return;
            }

            //Olreans interface authorization verification
            var authorised = this._authorisation.Authorise(context.HttpContext.User, routeResponse.Data);

            if (authorised.IsError)
            {
                _logger.LogWarning("error orleas authorising user scopes");
                SetPipelineError(context, authorised.Errors);
                return;
            }

            var clientBuilderResponse = _clusterClientBuilder.Build(routeResponse.Data, context);

            if (clientBuilderResponse.IsError)
            {
                Logger.LogDebug("IClusterClientBuilder Building Cluster Client and connecting Orleans error");
                SetPipelineError(context, routeResponse.Errors);
                return;
            }

            //Get a Grain instance
            var grainResponse = this._grainReference.GetGrainReference(routeResponse.Data);

            if (grainResponse.IsError)
            {
                Logger.LogDebug("IGrainReference Get a Orleas Grain instance error");
                SetPipelineError(context, routeResponse.Errors);
                return;
            }

            try
            {
                //Orleans injects the DownstreamContext into the RequestContext when requested
                this._config.RequestContextInjection?.Invoke(context);
            }
            catch (Exception ex)
            {
                Logger.LogError("Orleans injects the DownstreamContext into the RequestContext when requested error", ex);
                SetPipelineError(context, new UnknownError("Orleans injects the DownstreamContext into the RequestContext when requested error"));
                return;
            }

            //Grain Dynamic request
            try
            {
                var resultResponse = await _grainInvoker.Invoke(grainResponse.Data, routeResponse.Data);

                if (resultResponse.IsError)
                {
                    Logger.LogDebug("IGrainMethodInvoker  Grain Dynamic request error");
                    SetPipelineError(context, resultResponse.Errors);
                    return;
                }
                Logger.LogDebug("setting http response message");
                context.HttpContext.Response.ContentType = resultResponse.Data.Content.ContentType;
                context.DownstreamResponse = new DownstreamResponse(resultResponse.Data.Content, resultResponse.Data.StatusCode, resultResponse.Data.Headers, "");
            }
            catch (Exception ex)
            {
                Logger.LogError($"Request Orleans Silo exception;Uri:{context.DownstreamRequest.ToUri()}", ex);
                throw new OrleansRequestException("Request Orleans Silo exception ");
            }
        }