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.
Best Answer
You can use
ReadAsAsync<T>
.NET 4 (you can do that without continuations as well)
.NET 4.5