Request.body in ASP. NET Core is a Stream, but it is a different stream--does not allow request.body.position=0, which means that it can only be read once, in order to read multiple times, you need to use Memor Ystream, see the question of 2 read request.body in Q-Net core
using (varnew MemoryStream ()) { Request.Body.CopyTo (buffer); 0 ; Buffer. CopyTo (writer. BaseStream); Console.WriteLine ("request.body:"); 0 ;
Read the blog yesterday Reading request body in ASP. NET core has been given a workaround for this issue in ASP.--enablerewind (), as long as the rewind function is enabled, you can let Requ Est. Body returns to normal Stream.
Using a very simple, reference namespace Microsoft.AspNetCore.Http.Internal, call Method Request.enablerewind (), let's take a look at the simple sample code
Public classhomecontroller:controller{ PublicIactionresult Index () {request.enablerewind (); Console.WriteLine ("request.body1:"); Request.Body.Position=0; Request.Body.CopyTo (Console.openstandardoutput ()); Console.WriteLine (); Console.WriteLine ("Request.body2:"); Request.Body.Position=0; Request.Body.CopyTo (Console.openstandardoutput ()); Console.WriteLine (); returnOk (); }}
Launch the above ASP. NET Core site and make a request with the Curl command
Curl-x post-d ' Hello World ' localhost:5000
The console will output the desired results.
Request.Body1:Hello WorldRequest.Body2:Hello World
Enablerewind has 2 parameters bufferthreshold and Bufferlimit. Bufferthreshold sets the Request.body maximum cache bytes (default is 30K), bytes that exceed this threshold are written to disk, Bufferlimit sets the maximum number of bytes allowed by Request.body (the default is null). Exceeding this limit, an exception System.IO.IOException will be thrown.
Enablerewind implementation source code see BufferingHelper.cs
Correct posture for reading request.body in ASP.