讀取請求體流的demo
public static async Task<string> GetBodyForm(this HttpContext http)
{
var content = string.Empty;
var request = http.Request;
try
{
request.Body.Position = 0;
using var reader = new StreamReader(request.Body, Encoding.UTF8, leaveOpen: true);
var strRequestBody = await reader.ReadToEndAsync();
Console.WriteLine("ok");
Console.WriteLine(strRequestBody == null ? "null" : strRequestBody);
request.Body.Position = 0;
}
catch (Exception ex)
{
Console.WriteLine("err");
Console.WriteLine(ex);
}
return content;
}
在ActionFilter中讀取Request.Body
public class ActionFilterTestA : ActionFilterAttribute
{
public override async void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("From Request Body---->");
Console.WriteLine(await context.HttpContext.GetBodyForm());
Console.WriteLine("From Request Body---->");
}
}
報錯,一般是在Request.Body處報NotSupportedException
解決方案
在自定義中間件中調(diào)用EnableBuffering()
app.Use(async (context, next) =>
{
context.Request.EnableBuffering();
await next();
});
疑問
(移除以上正確方案代碼) 為什么在ActionFilterTestA
中調(diào)用context.HttpContext.Request.EnableBuffering();
沒有效果?(沒有報錯,但是內(nèi)容為空字符串)
猜測
請求體流在ActionFilter之前,在自定義中間件之后被消耗。 中間件執(zhí)行順序
測試
// 取消模型綁定
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressInferBindingSourcesForParameters = true;
});
Request.Body的內(nèi)容打印成功。
推論
綁定模型時會消耗掉請求體流。
其他資料
https://markb.uk/asp-net-core-read-raw-request-body-as-string.html文章來源:http://www.zghlxwxcb.cn/news/detail-711718.html
結(jié)語
推薦還是通過中間件調(diào)用EnableBuffering
解決問題文章來源地址http://www.zghlxwxcb.cn/news/detail-711718.html
注意事項:
- 避免關(guān)閉StreamReader導(dǎo)致關(guān)閉了Stream,可以通過
leaveOpen: true
解決 - 重置Position = 0
到了這里,關(guān)于.net core讀取Response.Body的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!