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 ?

Upvotes: 3

Views: 464

Answers (1)

Wolfgang Ziegler
Wolfgang Ziegler

Reputation: 1685

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);

Upvotes: 4

Related Questions