Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 995
Kofi Sarfo Avatar asked Sep 13 '12 19:09

Kofi Sarfo


People also ask

How do I return content in HttpResponseMessage?

Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore. Now, you need to use the Content property to set the content of the message.

What is HttpResponseMessage in Web API?

HttpResponseMessage. If the action returns an HttpResponseMessage, Web API converts the return value directly into an HTTP response message, using the properties of the HttpResponseMessage object to populate the response. This option gives you a lot of control over the response message.


1 Answers

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>(); 
like image 198
Filip W Avatar answered Oct 26 '22 11:10

Filip W