Correct posture for reading request.body in ASP.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.