【发布时间】:2019-04-22 14:18:59
【问题描述】:
我正在尝试从 HttpRequest.Body 读取流数据,但我得到的是空字符串。 请求是从 .net 项目发送到这里的
HttpWebRequest request = null;
Uri uri = new Uri(**Endpoint**);
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(message);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
request.UseDefaultCredentials = true;
using (Stream writeStream = request.GetRequestStream()) {
writeStream.Write(bytes, 0, bytes.Length);
}
try {
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
return true;
} else {
return false;
}
} catch {
lock (endpointLock) {
_pushHttpEndpoint = null;
}
return false;
}
请求在此处发送。这是 .net core 2.1 应用程序。我正在尝试读取请求正文中的数据,但返回的是空的
[HttpPost]
public string Post()
{
var bodyStr = "";
var req = HttpContext.Request;
req.EnableRewind();
using (StreamReader reader
= new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
{
bodyStr = reader.ReadToEnd();
}
req.Body.Seek(0, SeekOrigin.Begin);
//do other stuff
return bodyStr;
}
有人可以帮我解决这个问题吗? 我们处于无法更改 .net 解决方案代码的位置。任何更改都应在 .net 核心解决方案方面进行。我们正在尝试用新的 api 代替现有的 Endpoint。 :(
【问题讨论】:
-
检查我的答案。我只是在 .Net Core 2.2 中做了同样的事情。它可能对你有用。
标签: asp.net-core asp.net-core-mvc httpwebrequest asp.net-core-webapi asp.net-core-2.1