Reading XML content from the body of a WebAPI call is interrupted from the very beginning

I am creating a kind of proxy service that should handle calls containing XML from the POST body to my WebAPI service and then POST to another service.

Odd is that when I receive an XML message from POST , the first part of the XML from the body is disconnected. Initially, I thought maybe the buffer size, or the message was too large, so I cut out a lot of the sent XML test message, reducing what was sent. However, XML is still being disabled in the same place.

I tried the following (2) methods for reading XML BODY in a WebAPI service, and the result is the same:

 var reader = new StreamReader(Request.Content.ReadAsStreamAsync().Result); string originalMessage = reader.ReadToEnd(); 

and

  var result = ""; Request.Content.ReadAsStreamAsync().ContinueWith(x => { using (var sr = new StreamReader(x.Result)) { result = sr.ReadToEnd(); } }); 

Here is a snippet of the source XML:

 <Message version="123" release="001" xmlns="http://www.mysite.com/schema"> <Header> <To Att1="A">001</To> <From Att2="B">002</From> <ID>9876</ID> 

Here is the beginning of the content after reading it in the WebAPI POST controller:

 </To> <From Att2="B">002</From> <ID>9876</ID> 

See how it starts with the 'close' tag of the <To> element? This is obviously not the beginning of the XML that it was sent.

Even stranger is the "Size of the content" when checking before it is sent, and after - 4188 on both sides. Something else interesting is that I have an old .asmx tester (as opposed to a web API service) that does the same thing. When I read the incoming XML message in this application using the following:

  // Get raw request body Stream receiveStream = HttpContext.Current.Request.InputStream; // Move to beginning of input stream and read receiveStream.Position = 0; using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { // Load into XML document xmlSoapRequest.Load(readStream); } 

... I see the full XML message. Therefore, I’m not sure why .asmx can fully read it, but not the WebAPI service.

What am I doing wrong in my WebAPI POST call, where I do not see the complete XML message that was sent in the request body?

+6
source share
1 answer

Well, I understood the question, but not 100% sure of the reason. The parameter I used for POST was one of the fields:

 public HttpResponseMessage Post([FromBody]string value) 

I changed it so that instead of asking instead of POST instead of asking:

 public HttpResponseMessage Post(HttpRequestMessage request) 

When I did the second option above, I started getting the whole XML object from the request, as expected.

+11
source

Source: https://habr.com/ru/post/957861/


All Articles