1

If a caller adds HttpContent:

using (var content = new MultipartFormDataContent()) 
{
  HttpContent additionalContent = StringContent("just a test");
  content.Add(additionalContent);

Which is then POST'ed, how does the receiver retrieve this additional content?

I've seen examples where people call Request.Content. However, HttpContent.Current.Request doesn't have a Content object.

The receiver is an [HttpPost] WebAPI.

4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • check this http://stackoverflow.com/questions/12494067/read-httpcontent-in-mvc-webapi-controller – PSK Jul 13 '16 at 04:39

2 Answers2

2

Use ReadAsMultipartAsync extension method for getting content parts and then ReadAsStringAsync for parsing string content:

var provider = await Request.Content.ReadAsMultipartAsync();
var content = provider.Contents.FirstOrDefault(); //assumed single content part has been sent
if (content != null)
{
    var result = await content.ReadAsStringAsync();
}
Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
  • Something about changing the method type to Task, which I don't want to do. – 4thSpace Jul 13 '16 at 16:56
  • What do you mean? How is this related? – Aleksey L. Jul 13 '16 at 18:26
  • This doesn't work in a method that returns HttpMessageResponse. I don't want to restructure the method just for this. – 4thSpace Jul 13 '16 at 18:28
  • If I add .Result, after a long time, an exception is thrown: task was cancelled. "one or more errors occurred". It's vague. I actually catch the error on the client side, even through that line is wrapped in a try/catch on the webapi side. – 4thSpace Jul 13 '16 at 18:37
  • And any real reason to not convert web api action to `async Task`? – Aleksey L. Jul 13 '16 at 18:49
  • I don't want to waste time debugging all the side affects. But what difference does it make if that code is throwing some unknown exception? – 4thSpace Jul 13 '16 at 19:36
  • First try the `async` version - I'm pretty sure there will be no exception. – Aleksey L. Jul 13 '16 at 19:38
  • I added async and await from your code above. Once it hits Request.Content.ReadAsMultipartAsync, it skips all the other code and lands on my return (statuscode). So nothing is processed and the client gets a false statuscode. – 4thSpace Jul 13 '16 at 19:41
  • Sorry, I had a conditional that was preventing the code from running. It is working now. Thanks. – 4thSpace Jul 13 '16 at 19:46
-1

I think the body of your request is nothing but content of request. Please cross check using F12 developers tools->Network-> Request's response section or body section.

ravindra
  • 322
  • 3
  • 14