22
かなり一般的なCRUD操作では、IDが設定されたオブジェクトが永続化されます。WEB APIを使用している場合、POSTからHttpResponseMessageからコンテンツを抽出するにはどうすればよいですか?
したがって、オブジェクトを受け入れ、JSONをシリアル化し、HttpStatusCodeを使用してHttpStatusCodeを返すPostメソッドを作成し、同じオブジェクトに設定したIDがnullから整数に更新された場合、そのId値を取得するにはHttpClientを使用しますか?
おそらくかなり単純ですが、私が見るのは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のが触発ようです。いくつかの公式のサンプルをCodePlexの上がある -
(あなたが同様に継続せずにそれを行うことができます)を使用することができますここでは.NET 4.0と4.5の両方についてhttp://blogs.msdn.com/b/webdev/archive/2012/08/26/asp-net-web-api-and-httpclient-samples.aspx –
はい。ありがとうございました。これらのサンプルは、私が探していたものとまったく同じものでした。何とかそれらを逃した。 – ofraski