.Net Core 對於body多次讀取,.net core2.0 使用EnableRewind(),.net core 3.0使用EnableBuffering(),該參數在第一次讀取body之前開啟,之后body信息可以多次讀取;core時代取消了之前的stream.position=0寫法,雖然var byts = new byte[request.ContentLength.Value]中的request.ContentLength.Value超過1024語法並沒有錯,但是對於流讀取的話,一次最多是1024,如果一次需要讀取的大於1024,也不會報錯,會截斷,就是讀取的信息不全。這個是我在工作中對接ERP系統吸取的教訓,搞了好久才發現內容被截斷了,現在分享給大家,讓你們少走點彎路。
一、錯誤寫法
// 獲取請求參數
var request = actionContext.HttpContext.Request;
request.EnableBuffering();
var stream = actionContext.HttpContext.Request.Body;
// 限制 讀取 丟失
var byts = new byte[request.ContentLength.Value];
stream.Read(byts, 0, byts.Length);
var postJson = Encoding.UTF8.GetString(byts);
actionContext.HttpContext.Request.Body.Position = 0
二、正確寫法
// 獲取請求參數
var request = context.HttpContext.Request;
request.EnableBuffering();
var postJson = string.Empty;
if (request?.ContentLength > 0)
{
// 使用這個方式讀取,並且使用異步
StreamReader streamReader = new StreamReader(request.Body, Encoding.UTF8);
postJson = streamReader.ReadToEndAsync().Result;
}
request.Body.Position = 0;