c# net core http middleware code example
Example: c# core middleware request.body
public class RequestApplicationLogMiddleware
{
private readonly RequestDelegate _next;
private WebApiTemplate.Interface.ISession _session;
public RequestApplicationLogMiddleware(RequestDelegate next, WebApiTemplate.Interface.ISession session)
{
this._session=session;
this._next = next;
}
public async Task InvokeAsync(HttpContext context, IApplicationLog log)
{
_session.Id=Guid.NewGuid().ToString();
if (context.Request.Path.Value.Contains("api"))
{
var bodyStr = "";
var req = context.Request;
req.EnableRewind();
using (StreamReader reader
= new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
{
bodyStr = reader.ReadToEnd();
}
req.Body.Position = 0;
log.SaveRqst(new { Header = context.Request.Headers, Data = bodyStr }, context.Request.Path);
}
await _next(context);
}
}