Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read Request.Content in ASP.NET WebApi controller

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?

like image 940
mcintyre321 Avatar asked Sep 11 '25 04:09

mcintyre321


1 Answers

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;
like image 69
JeffR Avatar answered Sep 12 '25 17:09

JeffR