c# - 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.
解决方案
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();
});
}
另一方面,如果您想从控制器操作转发您的请求,则必须复制该请求。
推荐阅读
- typescript - 如何根据查询投影定义类型
- python - 如何在具有属性层次结构的 DSL 查询中添加权重
- mysql - MYSQL:停止 IFNULL 返回 null 的“空”行
- python - 在没有原型和标头的情况下,如何在 Python 中查找嵌入对象的数据类型
- reactjs - 从 React-Table 中的一行获取信息/数据/值
- python - 为 plotly 的 Figure show 方法定义全局配置值
- c++ - 为什么在使用 FFTW 将(2d)IDFT 转换为 DFT 时,频域中的数据会“镜像”?
- service - 使用 PATCH 方法更新 SAP BUSINESS ONE 服务层上的 salesOrderLines 时出现问题
- html - 使用悬停图像更改制作一排图像的更清洁方法?
- google-apps-script - Google 脚本无法写入/读取 Google 工作表并为 getValue() 提供错误“异常:输入数字”