I found the request in asp.net core custom middleware can be only read once, and after that I have to manually set the request back to the Request.Body. Is this recommended way to read the request?
public async Task Invoke(HttpContext context)
{
var request = context.Request;
string xmlstring;
using (System.IO.MemoryStream m = new System.IO.MemoryStream())
{
try
{
if (request.Body.CanSeek == true) request.Body.Position = 0;
request.Body.CopyTo(m);
xmlstring = System.Text.Encoding.UTF8.GetString(m.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(xmlstring));
await _next.Invoke(context);
}
I tried to "copy" the stream to another one, but doesn't help. I doubt all custom middleware has this step of setting request body back, so here to ask if I do it in proper way.