好的,所以我一直在绞尽脑汁,终其一生都无法理解为什么完全相同的一段代码在 .Net Core 2.2 中完美运行,但在 .Net Core 3.0 中返回一个空字符串。
我正在运行的一段代码是这样的:
public static async Task<string> GetRequestBodyAsync(this HttpRequest request,
Encoding encoding = null)
{
if (encoding == null) encoding = Encoding.UTF8;
var body = "";
request.EnableBuffering();
if (request.ContentLength == null || !(request.ContentLength > 0) || !request.Body.CanSeek) return body;
request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(request.Body, encoding, true, 1024, true))
body = await reader.ReadToEndAsync();
request.Body.Position = 0;
return body;
}
我这样称呼这个扩展:
var bodyContent = await Request.GetRequestBodyAsync();
var body = new MemoryStream(Encoding.UTF8.GetBytes(bodyContent));
在 .Net Core 2.2 中,我完全按照我的需要获取了发送的有效负载的正文,但在 .Net Core 3.0 中,我得到了一个空字符串。
我在我的启动中使用该扩展程序将 Newtonsoft 添加到我的 .Net Core 3.0 项目中,但如果我删除它,它仍然不起作用。
任何想法我可能做错了什么?
最佳答案
在启动类中添加这个中间件:
app.Use((context, next) =>
{
context.Request.EnableBuffering();
return next();
});
关于c# - .Net Core 3.0 中的请求正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59185410/