在“原样”转发整个接收到的请求。使用HttpClient [英] Forwarding the entire received request "as is" using HttpClient

查看:399
本文介绍了在“原样”转发整个接收到的请求。使用HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个瘦的前端API Web服务,该服务对接收到的数据进行一些预处理,然后使用HttpClient将数据发送到我的后端API Web服务。

I have a thin frontend API web service that does some preprocessing on the received data and then sends the data to my backend API web service using HttpClient.

有一些复杂的情况,当请求包含带有JSON和文件的多部分数据时,我根本不想在前端进行解析。后端将完成工作。

There are some complex cases when a request contains multipart data with JSON and files, and I don't want to parse it at all in the frontend. The backend will do the job.

因此,我想按原样接受请求-尽可能原始(不关心其内容以及它是否是多部分内容)

So, I would like to take the request "as is" - as raw as possible (not caring about its contents and whether it's multipart or not) and just forward it to the backend API.

我尝试了以下操作:

var msg = new HttpRequestMessage(HttpMethod.Post, resourceUrl);
msg.Content = new StreamContent(request.Body);
var apiResponse = await _httpClient.SendAsync(msg);

但是后端Web服务接收到一个长度为0的空请求正文。

but the backend web service receives an empty request body with 0 length.

如何转发整个请求正文,而不必分析它并重新组装一个新的请求正文?

推荐答案

您需要设置 msg.Content.ContentLength 才能正常工作。将 ContentType 和其他内容标头从请求复制到 msg.Content 也是一个好主意,以便您的后端服务知道如何解析它。

You need to set msg.Content.ContentLength for this to work correctly. It's also a good idea to copy ContentType and other content headers from the request into msg.Content, so that your backend service knows how to parse it.

这篇关于在“原样”转发整个接收到的请求。使用HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆