3

Given an ASP.NET Core Web API, if I receive a request to one of the endpoints:

Q: How could I pass (resend) the same request to another external API? All the request information(headers, body, search parameters, etc) should be preserved.

Q: Is there a way to do it without having to reconstruct the entire request with HttpClient? If no, is there a tool/library that can read the HttpContext and reconstruct the request using HttpClient?

I would also like to be able to do some operations in between the requests.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Chris
  • 6,105
  • 6
  • 38
  • 55
  • 1
    Possible duplicate of [Relaying a request in asp.net (Forwarding a request)](https://stackoverflow.com/questions/697177/relaying-a-request-in-asp-net-forwarding-a-request) – demoncrate Oct 23 '19 at 13:07

1 Answers1

3

ProxyKit is a dotnet core reverse proxy that allows you to forward requests to an upstream server, you can also modify the requests and responses.

Conditional forwarding example:

public void Configure(IApplicationBuilder app)
{
    // Forwards the request only when the host is set to the specified value
    app.UseWhen(
        context => context.Request.Host.Host.Equals("api.example.com"),
        appInner => appInner.RunProxy(context => context
            .ForwardTo("http://localhost:5001")
            .AddXForwardedHeaders()
            .Send()));
}

Modify request example:

public void Configure(IApplicationBuilder app)
{
    // Inline
    app.RunProxy(context =>
    {
        var forwardContext = context.ForwardTo("http://localhost:5001");
        if (forwardContext.UpstreamRequest.Headers.Contains("X-Correlation-ID"))
        {
            forwardContext.UpstreamRequest.Headers.Add("X-Correlation-ID", Guid.NewGuid().ToString());
        }
        return forwardContext.Send();
    });
}

If on the other hand you want to forward your request from a controller action, you will have to copy the request.

Markus Dresch
  • 5,290
  • 3
  • 20
  • 40