public ForwarderMiddleware(RequestDelegate next, ILogger <ForwarderMiddleware> logger, IHttpForwarder forwarder, IRandomFactory randomFactory)
 {
     _next          = next ?? throw new ArgumentNullException(nameof(next));
     _logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     _forwarder     = forwarder ?? throw new ArgumentNullException(nameof(forwarder));
     _randomFactory = randomFactory ?? throw new ArgumentNullException(nameof(randomFactory));
 }
Beispiel #2
0
    private void ConfigureReverseProxy(IApplicationBuilder app, IHttpForwarder forwarder)
    {
        var mappings = _options.GetReverseProxyMappings();

        if (mappings?.Any() == true)
        {
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            var requestOptions = new ForwarderRequestConfig {
                ActivityTimeout = TimeSpan.FromSeconds(100)
            };

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                foreach (var mapping in mappings)
                {
                    endpoints.Map(mapping.Key, async httpContext =>
                    {
                        await forwarder.SendAsync(httpContext, mapping.Value, httpClient, requestOptions);
                    });
                }
            });
        }
    }
Beispiel #3
0
        public void Configure(IApplicationBuilder app, IHttpForwarder forwarder)
        {
            app.UseHsts();
            app.UseHttpsRedirection();

            app.UseHosting(forwarder);
        }
Beispiel #4
0
 public PersistentSubscriptionController(IHttpForwarder httpForwarder, IPublisher publisher,
                                         IPublisher networkSendQueue)
     : base(publisher)
 {
     _httpForwarder    = httpForwarder;
     _networkSendQueue = networkSendQueue;
 }
Beispiel #5
0
    public void Configure(IApplicationBuilder app, IHttpForwarder forwarder)
    {
        if (_options.EnableCors == true)
        {
            app.UseCors(corsPolicy =>
            {
                corsPolicy.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            });
        }
        app.UseStatusCodePages("text/html",
                               "<html><head><title>Error {0}</title></head><body><h1>HTTP {0}</h1></body></html>");

        app.UseDeveloperExceptionPage();

        ConfigureReverseProxy(app, forwarder);

        var pathBase = _options.GetPathBase();

        if (!string.IsNullOrEmpty(pathBase))
        {
            app.Map(pathBase, ConfigureFileServer);
        }
        else
        {
            ConfigureFileServer(app);
        }
    }
Beispiel #6
0
 public void Register(
     TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService,
     ITimeProvider timeProvider, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendService)
 {
     _projections = new EventStore.Projections.Core.Projections(
         db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendService,
         projectionWorkerThreadCount: _projectionWorkerThreadCount, runProjections: _runProjections);
 }
Beispiel #7
0
 public void Register(
     TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService,
     ITimeProvider timeProvider, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendService)
 {
     _projections = new EventStore.Projections.Core.Projections(
         db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendService,
         projectionWorkerThreadCount: _projectionWorkerThreadCount, runProjections: _runProjections);
 }
Beispiel #8
0
        public ProjectionsController(IHttpForwarder httpForwarder, IPublisher publisher, IPublisher networkSendQueue)
            : base(publisher)
        {
            _httpForwarder = httpForwarder;

            _clusterNodeJs = new MiniWeb("/web/es/js/projections", Locations.ProjectionsDirectory);

            _networkSendQueue = networkSendQueue;
            _miniWebPrelude   = new MiniWeb("/web/es/js/projections/v8/Prelude", Locations.PreludeDirectory);
        }
Beispiel #9
0
        public static IApplicationBuilder UseHosting(this IApplicationBuilder app, IHttpForwarder forwarder)
        {
            var hosting = app.ApplicationServices.GetService <Hosting>();

            app.UseRouting();

            hosting.UseHostingOnApplicationBuilder(app, forwarder);

            return(app);
        }
Beispiel #10
0
 public Projections(
     TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
     IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue,
     int projectionWorkerThreadCount, RunProjections runProjections)
 {
     _projectionWorkerThreadCount = projectionWorkerThreadCount;
     SetupMessaging(
         db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendQueue,
         runProjections);
 }
        /// <summary>
        /// Forwards the incoming request to the destination server, and the response back to the client.
        /// </summary>
        /// <param name="context">The HttpContext to forward.</param>
        /// <param name="destinationPrefix">The url prefix for where to forward the request to.</param>
        /// <param name="httpClient">The HTTP client used to forward the request.</param>
        /// <param name="requestConfig">Config for the outgoing request.</param>
        /// <returns>The status of a forwarding operation.</returns>
        public static ValueTask <ForwarderError> SendAsync(this IHttpForwarder forwarder, HttpContext context, string destinationPrefix,
                                                           HttpMessageInvoker httpClient, ForwarderRequestConfig requestConfig)
        {
            if (forwarder is null)
            {
                throw new ArgumentNullException(nameof(forwarder));
            }

            return(forwarder.SendAsync(context, destinationPrefix, httpClient, requestConfig, HttpTransformer.Default));
        }
Beispiel #12
0
        public AtomController(IHttpForwarder httpForwarder, IPublisher publisher, IPublisher networkSendQueue, bool disableHTTPCaching = false) : base(publisher)
        {
            _httpForwarder    = httpForwarder;
            _networkSendQueue = networkSendQueue;

            if (disableHTTPCaching)
            {
                // ReSharper disable once RedundantNameQualifier
                Transport.Http.Configure.DisableHTTPCaching = true;
            }
        }
Beispiel #13
0
        public Projections(
            TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
            IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue,
            int projectionWorkerThreadCount, RunProjections runProjections)
        {
            _projectionWorkerThreadCount = projectionWorkerThreadCount;
            SetupMessaging(
                db, mainQueue, mainBus, timerService, timeProvider, httpForwarder, httpServices, networkSendQueue,
                runProjections);

        }
 public static ProjectionManagerNode Create(
     TFChunkDb db, QueuedHandler inputQueue, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue,
     IPublisher[] queues, RunProjections runProjections)
 {
     var projectionManagerNode = new ProjectionManagerNode(inputQueue, queues, runProjections);
     var projectionsController = new ProjectionsController(httpForwarder, inputQueue, networkSendQueue);
     foreach (var httpService in httpServices)
     {
         httpService.SetupController(projectionsController);
     }
     return projectionManagerNode;
 }
Beispiel #15
0
        public static ProjectionManagerNode Create(
            TFChunkDb db, QueuedHandler inputQueue, IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue,
            IPublisher[] queues, RunProjections runProjections)
        {
            var projectionManagerNode = new ProjectionManagerNode(inputQueue, queues, runProjections);
            var projectionsController = new ProjectionsController(httpForwarder, inputQueue, networkSendQueue);

            foreach (var httpService in httpServices)
            {
                httpService.SetupController(projectionsController);
            }
            return(projectionManagerNode);
        }
Beispiel #16
0
        public ProjectionsController(IHttpForwarder httpForwarder, IPublisher publisher, IPublisher networkSendQueue)
            : base(publisher)
        {
            _httpForwarder = httpForwarder;

            var singleNodeFSRoot = MiniWeb.GetWebRootFileSystemDirectory("EventStore.SingleNode.Web");

            _singleNodeJs = new MiniWeb("/web/es/js/projections", Path.Combine(singleNodeFSRoot, Path.Combine("singlenode-web", "js", "projections")));

            var fileSystemWebRoot = MiniWeb.GetWebRootFileSystemDirectory("EventStore.Projections.Core");

            _networkSendQueue = networkSendQueue;
            _miniWebPrelude   = new MiniWeb("/web/es/js/projections/v8/Prelude", Path.Combine(fileSystemWebRoot, @"Prelude"));
            _miniWebResources = new MiniWeb("/web/es/js/projections/resources", Path.Combine(fileSystemWebRoot, Path.Combine("web-resources", "js")));
        }
Beispiel #17
0
        public ProjectionsController(IHttpForwarder httpForwarder, IPublisher publisher, IPublisher networkSendQueue)
            : base(publisher)
        {
            _httpForwarder = httpForwarder;

            var clusterNodeFSRoot = MiniWeb.GetWebRootFileSystemDirectory();

            _clusterNodeJs = new MiniWeb("/web/es/js/projections", Path.Combine(clusterNodeFSRoot, Path.Combine("projections")));

            var fileSystemWebRoot = MiniWeb.GetWebRootFileSystemDirectory();

            _networkSendQueue = networkSendQueue;
            _miniWebPrelude   = new MiniWeb("/web/es/js/projections/v8/Prelude", Path.Combine(fileSystemWebRoot, @"Prelude"));
            _miniWebResources = new MiniWeb("/web/es/js/projections/resources", Path.Combine(fileSystemWebRoot, Path.Combine("web-resources", "js")));
        }
 public StandardComponents(
     TFChunkDb db,
     QueuedHandler mainQueue,
     ISubscriber mainBus,
     TimerService timerService,
     ITimeProvider timeProvider,
     IHttpForwarder httpForwarder,
     HttpService[] httpServices,
     IPublisher networkSendService)
 {
     _db = db;
     _mainQueue = mainQueue;
     _mainBus = mainBus;
     _timerService = timerService;
     _timeProvider = timeProvider;
     _httpForwarder = httpForwarder;
     _httpServices = httpServices;
     _networkSendService = networkSendService;
 }
Beispiel #19
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="blazorProxyService">The <see cref="Service"/></param>
 /// <param name="config">The <see cref="ProxyConfig"/></param>
 /// <param name="httpClient">HttpClient for forwarding requests.</param>
 /// <param name="forwarder">The YARP forwarder.</param>
 /// <param name="cache">The cache used for storing session information.</param>
 /// <param name="aesCipher">The <see cref="AesCipher"/> used for cookie encryption.</param>
 /// <param name="dnsClient">The <see cref="LookupClient"/> for service discovery.</param>
 /// <param name="sessionTransformer">The <see cref="SessionTransformer"/>.</param>
 public BlazorController(
     Service blazorProxyService,
     ProxyConfig config,
     HttpMessageInvoker httpClient,
     IHttpForwarder forwarder,
     IDistributedCache cache,
     AesCipher aesCipher,
     LookupClient dnsClient,
     SessionTransformer sessionTransformer)
 {
     this.blazorProxyService = blazorProxyService;
     this.config             = config;
     this.httpClient         = httpClient;
     this.forwarder          = forwarder;
     this.cache       = cache;
     this.cipher      = aesCipher;
     this.transformer = sessionTransformer;
     this.dnsClient   = dnsClient;
 }
 public StandardComponents(
     TFChunkDb db,
     IQueuedHandler mainQueue,
     ISubscriber mainBus,
     TimerService timerService,
     ITimeProvider timeProvider,
     IHttpForwarder httpForwarder,
     HttpService[] httpServices,
     IPublisher networkSendService)
 {
     _db                 = db;
     _mainQueue          = mainQueue;
     _mainBus            = mainBus;
     _timerService       = timerService;
     _timeProvider       = timeProvider;
     _httpForwarder      = httpForwarder;
     _httpServices       = httpServices;
     _networkSendService = networkSendService;
 }
Beispiel #21
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="NeonSsoSessionProxyService"></param>
 /// <param name="httpClient"></param>
 /// <param name="forwarder"></param>
 /// <param name="cache"></param>
 /// <param name="aesCipher"></param>
 /// <param name="dexClient"></param>
 public AuthController(
     Service NeonSsoSessionProxyService,
     HttpMessageInvoker httpClient,
     IHttpForwarder forwarder,
     IDistributedCache cache,
     AesCipher aesCipher,
     DexClient dexClient,
     SessionTransformer sessionTransformer,
     DistributedCacheEntryOptions cacheOptions
     )
 {
     this.NeonSsoSessionProxyService = NeonSsoSessionProxyService;
     this.httpClient   = httpClient;
     this.forwarder    = forwarder;
     this.cache        = cache;
     this.cipher       = aesCipher;
     this.transformer  = sessionTransformer;
     this.dexClient    = dexClient;
     this.cacheOptions = cacheOptions;
 }
Beispiel #22
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        public void Configure(IApplicationBuilder app, IHttpForwarder httpProxy)
        {
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            var transformBuilder = app.ApplicationServices.GetRequiredService <ITransformBuilder>();
            var transformer      = transformBuilder.Create(context =>
            {
                context.AddQueryRemoveKey("param1");
                context.AddQueryValue("area", "xx2", false);
                context.AddOriginalHost(false);
            });

            // or var transformer = new CustomTransformer();
            // or var transformer = HttpTransformer.Default;

            var requestOptions = new ForwarderRequestConfig {
                Timeout = TimeSpan.FromSeconds(100)
            };

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    await httpProxy.SendAsync(httpContext, "https://example.com", httpClient, requestOptions, transformer);
                    var errorFeature = httpContext.GetForwarderErrorFeature();
                    if (errorFeature != null)
                    {
                        var error     = errorFeature.Error;
                        var exception = errorFeature.Exception;
                    }
                });
            });
        }
Beispiel #23
0
        private void SetupMessaging(
            TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
            IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue, RunProjections runProjections)
        {
            _coreQueues        = new List <QueuedHandler>();
            _managerInputBus   = new InMemoryBus("manager input bus");
            _managerInputQueue = new QueuedHandler(_managerInputBus, "Projections Master");
            while (_coreQueues.Count < _projectionWorkerThreadCount)
            {
                var coreInputBus = new InMemoryBus("bus");
                var coreQueue    = new QueuedHandler(
                    coreInputBus, "Projection Core #" + _coreQueues.Count, groupName: "Projection Core");
                var projectionNode = new ProjectionWorkerNode(db, coreQueue, timeProvider, runProjections);
                projectionNode.SetupMessaging(coreInputBus);


                var forwarder = new RequestResponseQueueForwarder(
                    inputQueue: coreQueue, externalRequestQueue: mainQueue);
                // forwarded messages
                projectionNode.CoreOutput.Subscribe <ClientMessage.ReadEvent>(forwarder);
                projectionNode.CoreOutput.Subscribe <ClientMessage.ReadStreamEventsBackward>(forwarder);
                projectionNode.CoreOutput.Subscribe <ClientMessage.ReadStreamEventsForward>(forwarder);
                projectionNode.CoreOutput.Subscribe <ClientMessage.ReadAllEventsForward>(forwarder);
                projectionNode.CoreOutput.Subscribe <ClientMessage.WriteEvents>(forwarder);


                if (runProjections >= RunProjections.System)
                {
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.StateReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.ResultReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.StatisticsReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.Started>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.Stopped>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.Faulted>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.Prepared>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <CoreProjectionManagementMessage.SlaveProjectionReaderAssigned>(
                            _managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create <ProjectionManagementMessage.ControlMessage>(_managerInputQueue));
                }
                projectionNode.CoreOutput.Subscribe <TimerMessage.Schedule>(timerService);


                projectionNode.CoreOutput.Subscribe(Forwarder.Create <Message>(coreQueue)); // forward all

                coreInputBus.Subscribe(new UnwrapEnvelopeHandler());

                _coreQueues.Add(coreQueue);
            }

            _managerInputBus.Subscribe(
                Forwarder.CreateBalancing <FeedReaderMessage.ReadPage>(_coreQueues.Cast <IPublisher>().ToArray()));

            _projectionManagerNode = ProjectionManagerNode.Create(
                db, _managerInputQueue, httpForwarder, httpServices, networkSendQueue,
                _coreQueues.Cast <IPublisher>().ToArray(), runProjections);
            _projectionManagerNode.SetupMessaging(_managerInputBus);
            {
                var forwarder = new RequestResponseQueueForwarder(
                    inputQueue: _managerInputQueue, externalRequestQueue: mainQueue);
                _projectionManagerNode.Output.Subscribe <ClientMessage.ReadEvent>(forwarder);
                _projectionManagerNode.Output.Subscribe <ClientMessage.ReadStreamEventsBackward>(forwarder);
                _projectionManagerNode.Output.Subscribe <ClientMessage.ReadStreamEventsForward>(forwarder);
                _projectionManagerNode.Output.Subscribe <ClientMessage.WriteEvents>(forwarder);
                _projectionManagerNode.Output.Subscribe(
                    Forwarder.Create <ProjectionManagementMessage.RequestSystemProjections>(mainQueue));
                _projectionManagerNode.Output.Subscribe(Forwarder.Create <Message>(_managerInputQueue));

                _projectionManagerNode.Output.Subscribe <TimerMessage.Schedule>(timerService);

                // self forward all

                mainBus.Subscribe(Forwarder.Create <SystemMessage.StateChangeMessage>(_managerInputQueue));
                _managerInputBus.Subscribe(new UnwrapEnvelopeHandler());
            }
        }
Beispiel #24
0
        private void SetupMessaging(
            TFChunkDb db, QueuedHandler mainQueue, ISubscriber mainBus, TimerService timerService, ITimeProvider timeProvider,
            IHttpForwarder httpForwarder, HttpService[] httpServices, IPublisher networkSendQueue, RunProjections runProjections)
        {
            _coreQueues = new List<QueuedHandler>();
            _managerInputBus = new InMemoryBus("manager input bus");
            _managerInputQueue = new QueuedHandler(_managerInputBus, "Projections Master");
            while (_coreQueues.Count < _projectionWorkerThreadCount)
            {
                var coreInputBus = new InMemoryBus("bus");
                var coreQueue = new QueuedHandler(
                    coreInputBus, "Projection Core #" + _coreQueues.Count, groupName: "Projection Core");
                var projectionNode = new ProjectionWorkerNode(db, coreQueue, timeProvider, runProjections);
                projectionNode.SetupMessaging(coreInputBus);


                var forwarder = new RequestResponseQueueForwarder(
                    inputQueue: coreQueue, externalRequestQueue: mainQueue);
                // forwarded messages
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadEvent>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.ReadAllEventsForward>(forwarder);
                projectionNode.CoreOutput.Subscribe<ClientMessage.WriteEvents>(forwarder);


                if (runProjections >= RunProjections.System)
                {
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.StateReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.ResultReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.StatisticsReport>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Started>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Stopped>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Faulted>(_managerInputQueue));
                    projectionNode.CoreOutput.Subscribe(
                        Forwarder.Create<CoreProjectionManagementMessage.Prepared>(_managerInputQueue));

                }
                projectionNode.CoreOutput.Subscribe(timerService);


                projectionNode.CoreOutput.Subscribe(Forwarder.Create<Message>(coreQueue)); // forward all

                coreInputBus.Subscribe(new UnwrapEnvelopeHandler());

                _coreQueues.Add(coreQueue);
            }

            _managerInputBus.Subscribe(
            Forwarder.CreateBalancing<FeedReaderMessage.ReadPage>(_coreQueues.Cast<IPublisher>().ToArray()));

            _projectionManagerNode = ProjectionManagerNode.Create(
                db, _managerInputQueue, httpForwarder, httpServices, networkSendQueue,
                _coreQueues.Cast<IPublisher>().ToArray(), runProjections);
            _projectionManagerNode.SetupMessaging(_managerInputBus);
            {
                var forwarder = new RequestResponseQueueForwarder(
                    inputQueue: _managerInputQueue, externalRequestQueue: mainQueue);
                _projectionManagerNode.Output.Subscribe<ClientMessage.ReadEvent>(forwarder);
                _projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsBackward>(forwarder);
                _projectionManagerNode.Output.Subscribe<ClientMessage.ReadStreamEventsForward>(forwarder);
                _projectionManagerNode.Output.Subscribe<ClientMessage.WriteEvents>(forwarder);
                _projectionManagerNode.Output.Subscribe(
                    Forwarder.Create<ProjectionManagementMessage.RequestSystemProjections>(mainQueue));
                _projectionManagerNode.Output.Subscribe(Forwarder.Create<Message>(_managerInputQueue));

                _projectionManagerNode.Output.Subscribe(timerService);

                // self forward all

                mainBus.Subscribe(Forwarder.Create<SystemMessage.StateChangeMessage>(_managerInputQueue));
                _managerInputBus.Subscribe(new UnwrapEnvelopeHandler());
            }
        }
Beispiel #25
0
 public UsersController(IHttpForwarder httpForwarder, IPublisher publisher, IPublisher networkSendQueue)
     : base(publisher)
 {
     _httpForwarder    = httpForwarder;
     _networkSendQueue = networkSendQueue;
 }
Beispiel #26
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        public void Configure(IApplicationBuilder app, IHttpForwarder forwarder)
        {
            // Configure our own HttpMessageInvoker for outbound calls for proxy operations
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            // Setup our own request transform class
            var transformer    = new CustomTransformer(); // or HttpTransformer.Default;
            var requestOptions = new ForwarderRequestConfig {
                Timeout = TimeSpan.FromSeconds(100)
            };

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.Map("/test/{**catch-all}", async httpContext =>
                {
                    var error = await forwarder.SendAsync(httpContext, "https://example.com", httpClient, requestOptions,
                                                          (context, proxyRequest) =>
                    {
                        // Customize the query string:
                        var queryContext = new QueryTransformContext(context.Request);
                        queryContext.Collection.Remove("param1");
                        queryContext.Collection["area"] = "xx2";

                        // Assign the custom uri. Be careful about extra slashes when concatenating here.
                        proxyRequest.RequestUri = new Uri("https://example.com" + context.Request.Path + queryContext.QueryString);

                        // Suppress the original request header, use the one from the destination Uri.
                        proxyRequest.Headers.Host = null;

                        return(default);
                    });

                    // Check if the proxy operation was successful
                    if (error != ForwarderError.None)
                    {
                        var errorFeature = httpContext.Features.Get <IForwarderErrorFeature>();
                        var exception    = errorFeature.Exception;
                    }
                });


                // When using IHttpForwarder for direct forwarding you are responsible for routing, destination discovery, load balancing, affinity, etc..
                // For an alternate example that includes those features see BasicYarpSample.
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    var error = await forwarder.SendAsync(httpContext, "https://example.com", httpClient, requestOptions, transformer);
                    // Check if the proxy operation was successful
                    if (error != ForwarderError.None)
                    {
                        var errorFeature = httpContext.Features.Get <IForwarderErrorFeature>();
                        var exception    = errorFeature.Exception;
                    }
                });
            });
 /// <summary>
 /// Forwards the incoming request to the destination server, and the response back to the client.
 /// </summary>
 /// <param name="context">The HttpContext to forward.</param>
 /// <param name="destinationPrefix">The url prefix for where to forward the request to.</param>
 /// <param name="httpClient">The HTTP client used to forward the request.</param>
 /// <param name="requestConfig">Config for the outgoing request.</param>
 /// <param name="requestTransform">Transform function to apply to the forwarded request.</param>
 /// <returns>The status of a forwarding operation.</returns>
 public static ValueTask <ForwarderError> SendAsync(this IHttpForwarder forwarder, HttpContext context, string destinationPrefix,
                                                    HttpMessageInvoker httpClient, ForwarderRequestConfig requestConfig, Func <HttpContext, HttpRequestMessage, ValueTask> requestTransform)
 {
     return(forwarder.SendAsync(context, destinationPrefix, httpClient, requestConfig, new RequestTransformer(requestTransform)));
 }
 public PersistentSubscriptionController(IHttpForwarder httpForwarder, IPublisher publisher, IPublisher networkSendQueue)
     : base(publisher)
 {
     _httpForwarder = httpForwarder;
     _networkSendQueue = networkSendQueue;
 }