25

I am writing a proxy using WebApi in a TransferMode.Streamed HttpSelfHostConfiguration exe.

When I use fiddler to post to my ApiController, for some reason I cannot read the Request.Content - it returns "" even if I have POSTed data

public class ApiProxyController : ApiController
{

    public Task<HttpResponseMessage> Post(string path)
    {
        return Request.Content.ReadAsStringAsync().ContinueWith(s =>
        {
            var content = new StringContent(s.Result); //s.Result is ""
                CopyHeaders(Request.Content.Headers, content.Headers);
            return Proxy(path, content);
        }).Unwrap();
    }

    private Task<HttpResponseMessage> Proxy(string path, HttpContent content)
    {
        ...
    }
}

Here is my web request

POST http://localhost:3001/api/values HTTP/1.1
Host: localhost:3001
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type: application/json
Content-Length: 26

{ "text":"dfsadfsadfsadf"}

What I am doing wrong? Why is s.Result coming back as the empty string rather than the raw json?

10 Answers 10

35

I too struggled with this. ReadAsStringAsync and ReadAsAsync return a task object. Referencing the Result property returns the content. It may be referencing the Result property causes the async read request to block.

Example:

string str = response.Content.ReadAsStringAsync().Result;
2
  • 6
    use await instead of .Reseult
    – victor
    Oct 19, 2017 at 20:43
  • This is will only work in webapi if you reset the stream position. See the comment below made by Richard
    – mike gold
    Jul 5, 2018 at 22:26
21

I realise this is old, and has been answered, but for what it's worth, the reason you can't use ReadAsStringAsync() isn't because it 'eats the data' as has been suggested, it's because the content is being processed as a stream and since the data has been consumed by the message formatter the Position of the stream is already at the end.

In order to use ReadAsStringAsync() you first need to reset the content stream Position to the beginning.

I do it like this: response.RequestMessage.Content.ReadAsStreamAsync().Result.Seek( 0, System.IO.SeekOrigin.Begin ) because I only have the HttpResponseMessage, but if you have direct access to the HttpRequestMessage (as you do inside the Controller) you can use Request.Content.ReadAsStreamAsync().Result.Seek( 0, System.IO.SeekOrigin.Begin ) which is functionally equivalent I suppose.

Late Edit

Reading async streams with Result as above will cause deadlocks and blocked threads under a number of circumstances. If you have to read from an async stream in a synchronous way, it's better to use the form:

 new TaskFactory( CancellationToken.None, 
                  TaskCreationOptions.None, 
                  TaskContinuationOptions.None, 
                  TaskScheduler.Default )
      .StartNew<Task<TResult>>( func )
      .Unwrap<TResult>()
      .GetAwaiter()
      .GetResult();

where func is the async action you want to run, so in this case it would be something like async () => { await Request.Content.ReadAsStreamAsync(); } … in this way you can put the async parts of the method inside the StartNew part and properly unwrap any exceptions that happen when marshalling back to your synchronous code.

Better still, make the whole stack async.

5
  • 1
    I believe that if you're working with streamed request mode (which is important if writing a proxy and you don't want to consume lots of memory) you can't reset the stream location. Also, is it so terrible to use 'eaten' instead of 'consumed'? I doubt anyone thought something biological was going on. :) Jan 15, 2016 at 11:52
  • 1
    @mcintyre321 Lol. OK, 'consumed' want such a great choice of words was it. I guess 'eaten' implies to me that you can't get it back. FWIW I was able to reset the stream l location (which is buffered so not reading directly from the remote stream). To your point, I wonder what would happen with a very large request stream, where the data exceeds the buffer size? I did have a problem re-reading a multipart stream as it kept disposing itself. Ended up reading it into a memory stream first, them parsing it out into ReadAsMultipartAsnc() Jan 16, 2016 at 20:23
  • @RichardHauer: for some reason that returns an int instead of a string for me. Mar 30, 2019 at 18:00
  • @micahhoover The Seek() command returns an int (the new position within the stream), sure, but you probably don't need that value. After Seeking you can read the stream content using ReadAsStreamAsync(). Mar 31, 2019 at 1:52
  • @RichardHauer: thanks. It turns out my [FromBody] was iterating through the GetNext. I just dropped that, pulled it manually and everything worked. Apr 1, 2019 at 17:31
18

This signature for post eats the post data:

public HttpResponseMessage Post([FromBody]string postdata)

change it to:

public HttpResponseMessage Post()

then this call works fine to get the post data:

string str = response.Content.ReadAsStringAsync().Result;

Tested it my self. use the first signature, str is empty, use the second str has post data!

5
  • but then how can you get the postdata in the method? Nov 18, 2015 at 10:00
  • var request = await Request.Content.ReadAsStringAsync();
    – War
    Dec 3, 2015 at 14:08
  • This also applies to Controllers in MVC. Using FormCollection form will eat the content of a request.
    – jahu
    Apr 11, 2016 at 15:00
  • You just saved me countless hours of debugging. May 25, 2017 at 8:30
  • The async way would really be public async Task<HttpResponseMessage> Post() And then string str = await response.Content.ReadAsStringAsync(); Sep 27, 2017 at 15:04
5

I believe you are right about the ApiController eating the Request.Content. The "Request" object that you see in the ApiController is actually of type System.Net.Http.HttpRequestMessage. I was able to work around this issue but backing up to the System.Web.HttpRequest object like such:

Dim content as string
If HttpContext.Current.Request.InputStream.CanSeek Then
    HttpContext.Current.Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
End If
Using reader As New System.IO.StreamReader(HttpContext.Current.Request.InputStream)
    content = reader.ReadToEnd()
End Using

I don't know if the seek rewind is necessary but I put it in just in case.

2
  • It turned out that an ApiController was the wrong thing for building a proxy. In the end I used a MessageHandler and all was well. May 9, 2013 at 10:25
  • This works great. I only needed it for debugging so this was awesome.
    – BradLaney
    May 13, 2013 at 19:47
4

I got this working in the end by inheriting from the base interface instead of ApiController - I think the ApiController was modelbinding which was eating the response

edit: The right thing for building a proxy is a MessageHandler, not an ApiController

3
  • MSDN indicate that MessageHandlers should be used for cross-cutting concerns. For building proxies, standard MVC controllers ought to work fine.
    – arviman
    Jun 23, 2014 at 10:28
  • Not if you are building a streaming proxy. Jun 23, 2014 at 10:34
  • I mean, you could use the idea of blocking until you get the result as JeffR suggests, before you forward to the proxy. (I'm building something similar right now, and it's working great).
    – arviman
    Jun 23, 2014 at 10:41
2
  1. Request.Content.ReadAsStreamAsync().Result.Seek( 0, System.IO.SeekOrigin.Begin)
  2. new System.IO.StreamReader(Request.Content.ReadAsStreamAsync().Result).ReadToEnd()
0
1

This late addition to the answers here show how to read the POST data from WebAPI:

string postData;
using (var stream = await request.Content.ReadAsStreamAsync())
{
    stream.Seek(0, SeekOrigin.Begin);
    using (var sr = new StreamReader(stream))
    {
        postData = await sr.ReadToEndAsync();
    }
}
1

Try using CopyToAsync instead of ReadAsStringAsync seems to fix the problem

var ms = new MemoryStream();
await response.Content.CopyToAsync(ms);
ms.Seek(0, SeekOrigin.Begin);

var sr = new StreamReader(ms);
responseContent = sr.ReadToEnd();
0

Try replacing ReadAsStringAsync() with ReadAsAsync<string>().

0

You should use a complex type for your argument and then in the body use some json like

{ path: "c:..." }

Als use the

Content-Type: application/json; charset=UTF-8

header in your post request so that the web api knows that json is contained in the body

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.