How do I extract content from HttpResponseMessage from POST when using WEB API?

63,777

You can use ReadAsAsync<T>

.NET 4 (you can do that without continuations as well)

var resultTask = client.PostAsJsonAsync<MyObject>("http://localhost/api/service",new MyObject()).ContinueWith<HttpResponseMessage>(t => {
    var response = t.Result;
    var objectTask = response.Content.ReadAsAsync<MyObject>().ContinueWith<Url>(u => {
        var myobject = u.Result;
        //do stuff 
    });
});

.NET 4.5

    var response = await client.PostAsJsonAsync<MyObject>("http://localhost/api/service", new MyObject());
    var myobject = await response.Content.ReadAsAsync<MyObject>();
Share:
63,777

Related videos on Youtube

Kofi Sarfo
Author by

Kofi Sarfo

software developer

Updated on July 18, 2022

Comments

  • Kofi Sarfo
    Kofi Sarfo almost 2 years

    A pretty typical CRUD operation will result in an object having its Id set once persisted.

    So if I have Post method on the controller which accepts an object (JSON serialized, say) and returns an HttpResponseMessage with HttpStatusCode Created and Content set to the same object with Id updated from null to an integer, how then do I use HttpClient to get at that Id value?

    It's probably quite simple but all I see is System.Net.Http.StreamContent. Is it better just to return an Int from the post method?

    Thanks.

    Update (following answer):

    A working example...

    namespace TryWebAPI.Models {
        public class YouAreJoking {
            public int? Id { get; set; }
            public string ReallyRequiresFourPointFive { get; set; }
        }
    }
    
    namespace TryWebAPI.Controllers {
        public class RyeController : ApiController {
            public HttpResponseMessage Post([FromBody] YouAreJoking value) {
                //Patience simulated
                value.Id = 42;
    
                return new HttpResponseMessage(HttpStatusCode.Created) {
                    Content = new ObjectContent<YouAreJoking>(value,
                                new JsonMediaTypeFormatter(),
                                new MediaTypeWithQualityHeaderValue("application/json"))
                };
            }
        }
    }
    
    namespace TryWebApiClient {
        internal class Program {
            private static void Main(string[] args) {
                var result = CreateHumour();
                Console.WriteLine(result.Id);
                Console.ReadLine();
            }
    
            private static YouAreJoking CreateHumour() {
                var client = new HttpClient();
                var pennyDropsFinally = new YouAreJoking { ReallyRequiresFourPointFive = "yes", Id = null };
    
                YouAreJoking iGetItNow = null;
                var result = client
                    .PostAsJsonAsync("http://localhost:1326/api/rye", pennyDropsFinally)
                    .ContinueWith(x => {
                                    var response = x.Result;
                                    var getResponseTask = response
                                        .Content
                                        .ReadAsAsync<YouAreJoking>()
                                        .ContinueWith<YouAreJoking>(t => {
                                            iGetItNow = t.Result;
                                            return iGetItNow;
                                        }
                    );
    
                    Task.WaitAll(getResponseTask);
                    return x.Result;
                });
    
                Task.WaitAll(result);
                return iGetItNow;
            }
        }
    }
    

    Seems Node.js inspired.

  • Mark Jones
    Mark Jones over 11 years
    Indeed - There are some official samples on CodePlex here for both .NET 4.0 and 4.5 blogs.msdn.com/b/webdev/archive/2012/08/26/…
  • Kofi Sarfo
    Kofi Sarfo over 11 years
    Yep. Thanks Mark. Those samples were exactly what I was looking for. Missed them somehow.