Reputation: 6311
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.
Upvotes: 3
Views: 2509
Reputation: 5584
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.
Upvotes: 5