首页 > 解决方案 > Pass a request to another API

问题描述

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.

标签: c#asp.net-core.net-coreasp.net-core-webapi

解决方案


ProxyKit是一个 dotnet 核心反向代理,允许您将请求转发到上游服务器,您还可以修改请求和响应。

条件转发示例:

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()));
}

修改请求示例:

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();
    });
}

另一方面,如果您想从控制器操作转发您的请求,则必须复制该请求。


推荐阅读