asp.net core - Read request body twice -


i trying read body in middleware authentication purposes, when request gets api controller object empty body has been read. there anyway around this. reading body in middleware.

var buffer = new byte[ convert.toint32( context.request.contentlength ) ]; await context.request.body.readasync( buffer, 0, buffer.length ); var body = encoding.utf8.getstring( buffer ); 

if you're using application/x-www-form-urlencoded or multipart/form-data, can safely call context.request.readformasync() multiple times returns cached instance on subsequent calls.

if you're using different content type, you'll have manually buffer request , replace request body rewindable stream memorystream. here's how using inline middleware (you need register in pipeline):

app.use(next => async context => {     // keep original stream in separate     // variable restore later if necessary.     var stream = context.request.body;      // optimization: don't buffer request if     // there no stream or if rewindable.     if (stream == stream.null || stream.canseek) {         await next(context);          return;     }      try {         using (var buffer = new memorystream()) {             // copy request stream memory stream.             await stream.copytoasync(buffer);              // rewind memory stream.             buffer.position = 0l;              // replace request stream memory stream.             context.request.body = buffer;              // invoke rest of pipeline.             await next(context);         }     }      {         // restore original stream.         context.request.body = stream;     } }); 

you can use bufferinghelper.enablerewind() extension, part of microsoft.aspnet.http package: it's based on similar approach relies on special stream starts buffering data in memory , spools temp file on disk when threshold reached:

app.use(next => context => {     context.request.enablerewind();      return next(context); }); 

fyi: buffering middleware added vnext in future.


Comments