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博主「娃都会打酱油了」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/starfd/article/details/82734039
网友评论