SACenter/SA.WebApi/Middlewares/RequestMiddleware.cs

64 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}
}
}