Asp.net-Mvc
使用 WEB API 時,如何從 POST 中提取 HttpResponseMessage 的內容?
一個非常典型的 CRUD 操作將導致一個對象的 Id 設置一次。
因此,如果我在控制器上有 Post 方法,該方法接受一個對象(例如,JSON 序列化)並返回一個 HttpResponseMessage 並創建了 HttpStatusCode 並將 Content 設置為同一個對象,並將 Id 從 null 更新為整數,那麼我該如何使用 HttpClient 來獲取在那個 ID 值?
這可能很簡單,但我看到的只是 System.Net.Http.StreamContent。從 post 方法返回一個 Int 會更好嗎?
謝謝。
更新(以下答案):
一個工作範例…
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; } } }似乎受到 Node.js 的啟發。
您可以使用
ReadAsAsync<T>.NET 4(您也可以在沒有延續的情況下做到這一點)
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>();