2

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.

1 Answer 1

1

The correct steps should be:

  1. enablerewind
  2. read from body
  3. do rewind

Please note: without set body back to originalRequestBody, it will only work once, and if you try to call the same web api again, it will fail.

Please see below sample code

    public async Task Invoke(HttpContext context)
    {


        var originalRequestBody = context.Request.Body;

        context.Request.EnableRewind();

        try
        {


            using (System.IO.MemoryStream m = new MemoryStream())
            {
                context.Request.Body.CopyTo(m);

                var s = System.Text.Encoding.UTF8.GetString(m.ToArray());
            }

            //this line will rewind the request body, so it could be read again
            context.Request.Body.Position = 0;

            await _next(context);
        }
        catch (Exception ex)
        {

        }
        finally
        {
            //important, otherwise, even current request will succeed, following request will fail
            context.Request.Body = originalRequestBody;
        }

    }
Sign up to request clarification or add additional context in comments.

1 Comment

I would recommend to test this solution in a dummy project, rather than copy/paste to your existing projects. Prove the theory first and then identify why it is not working in real projec

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.