Dosyć typowa operacja CRUD spowoduje, że obiekt o ustawionym identyfikatorze zostanie utrwalony.Jak wyodrębnić zawartość z HttpResponseMessage z POST podczas korzystania z WEB API?
Więc jeśli mam metodę Post na kontroler, który akceptuje obiekt (JSON serializowane, powiedzmy) i zwraca HttpResponseMessage z HttpStatusCode Stworzone i zawartość zestaw do tego samego obiektu z Id zaktualizowane od null do liczby całkowitej, w jaki sposób to zrobić użyć HttpClient, aby uzyskać tę wartość Id?
To prawdopodobnie bardzo proste, ale widzę tylko System.Net.Http.StreamContent. Czy lepiej jest po prostu zwrócić Int z metody postu?
Dzięki.
Update (po odpowiedź):
przykład roboczych ...
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;
}
}
}
Wydaje node.js inspirowane.
Rzeczywiście - Istnieją pewne urzędowe próbki na CodePlex tutaj zarówno dla .NET 4.0 i 4.5 http://blogs.msdn.com/b/webdev/archive/2012/08/26/asp-net-web-api-and-httpclient-samples.aspx –
Tak. Dzięki Mark. Te próbki były dokładnie tym, czego szukałem. Jakoś ich nie otrzymałem. – ofraski