Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API Request Data error on second time

Strange Error.

var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(this.Request.Content.ReadAsStreamAsync().Result);

var xmlDoc1 = new System.Xml.XmlDocument();
xmlDoc1.Load(this.Request.Content.ReadAsStreamAsync().Result);

In WEB API, I try to load the POST data in to xmlXoc it is working good

When I try to load it again in to xmlDoc1 (new variable), I am getting a Root Element missing error.

I see that ReadAsStreamAsync is a Read-Only-Stream but why the error on the last line ?

like image 844
now he who must not be named. Avatar asked Mar 22 '26 13:03

now he who must not be named.


1 Answers

Save the Stream in a local variable and reset it to the beginning when reading it a second time.

var stream = this.Request.Content.ReadAsStreamAsync().Result

var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(stream);

// RESET 
stream.Position = 0;
var xmlDoc1 = new System.Xml.XmlDocument();
xmlDoc1.Load(stream);
like image 146
Wolfgang Ziegler Avatar answered Mar 25 '26 03:03

Wolfgang Ziegler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!