Alex Mirza
Alex Mirza

Reputation: 3

C# HttpClient PostAsJsonAsync -> Error reading string

Hi I try to call an web api by server side with:

using (var client = new HttpClient())
        {
            using (var rsp = client.PostAsJsonAsync<Request>(url, model).Result)
            {
                if (!rsp.IsSuccessStatusCode)
                {
                    // throw an appropriate exception
                }
                var result = rsp.Content.ReadAsAsync<string>().Result;
            }
        }

but I get error

Error reading string. Unexpected token: StartObject. Path '', line 1, position 1.

If I try to call same url from jQuery

$.post('http://localhost/api/Test')

the server return

 HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 25 Oct 2015 12:15:56 GMT
Content-Length: 104

{
  "Header": {
    "Token": "Response",
    "Timestamp": "2015-10-25T14:15:56.0092197+02:00"
  }
}

The "model" arrive on api controller but I can't get response from request.

Upvotes: 0

Views: 1621

Answers (1)

Todd Menier
Todd Menier

Reputation: 39289

ReadAsAsync<T> attempts to deserialize the response to type T. In this case, you're saying you want to deserialize JSON to a string, which doesn't really make sense. Either use a type matching the response (i.e. a custom data structure containing Header, Token, etc.) or use ReadAsStringAsync() if you really want to get a string.

Upvotes: 1

Related Questions