public async Task Invoke(HttpContext context)
{
try
{
var body = await ReadBodyAsync(context.Request);
LoggerInfo.Info($"請求接口:{context.Request.Path};請求體:{body}");
await requestDelegate(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task<string> ReadBodyAsync(HttpRequest request)
{
if (request.ContentLength > 0)
{
await EnableRewindAsync(request).ConfigureAwait(false);
var encoding = GetRequestEncoding(request);
return await this.ReadStreamAsync(request.Body, encoding).ConfigureAwait(false);
}
return null;
}
private Encoding GetRequestEncoding(HttpRequest request)
{
var requestContentType = request.ContentType;
var requestMediaType = requestContentType == null ? default(MediaType) : new MediaType(requestContentType);
var requestEncoding = requestMediaType.Encoding;
if (requestEncoding == null)
{
requestEncoding = Encoding.UTF8;
}
return requestEncoding;
}
private async Task EnableRewindAsync(HttpRequest request)
{
if (!request.Body.CanSeek)
{
request.EnableBuffering();
await request.Body.DrainAsync(CancellationToken.None);
request.Body.Seek(0L, SeekOrigin.Begin);
}
}
private async Task<string> ReadStreamAsync(Stream stream, Encoding encoding)
{
using (StreamReader sr = new StreamReader(stream, encoding, true, 1024, true))//這里注意Body部分不能隨StreamReader一起釋放
{
var str = await sr.ReadToEndAsync();
stream.Seek(0, SeekOrigin.Begin);//內容讀取完成后需要將當前位置初始化,否則后面的InputFormatter會無法讀取
return str;
}
}
————————————————
版權聲明:本文為CSDN博主「娃都會打醬油了」的原創(chuàng)文章蝗砾,遵循 CC 4.0 BY-SA 版權協(xié)議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/starfd/article/details/82734039