Search code examples
c#.netasp.net-web-apihttpcontent

How to get HttpContent from Request object?


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.


Solution

  • 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();
    }