64 lines
2.3 KiB
C#
64 lines
2.3 KiB
C#
namespace SA.WebApi.Middlewares
|
||
{
|
||
public class RequestMiddleware
|
||
{
|
||
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||
private readonly RequestDelegate _next;
|
||
|
||
public RequestMiddleware(RequestDelegate next)
|
||
{
|
||
_next = next;
|
||
}
|
||
|
||
public async Task Invoke(HttpContext httpContext)
|
||
{
|
||
//LogHelper.Info($"Request body: {await ReadBodyAsync(httpContext.Request)}");
|
||
logger.Trace($"Request body: {await ReadBodyAsync(httpContext.Request)}");
|
||
await _next.Invoke(httpContext);
|
||
}
|
||
|
||
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;
|
||
}
|
||
}
|
||
}
|
||
} |