非常典型的CRUD操作将导致对象在持久化后设置其Id。
因此,如果我在控制器上有Post方法,它接受一个对象(比如JSON序列化),并返回一个HttpResponseMessage,其中HttpStatusCode Created和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>
.NET4(您也可以在没有延续的情况下完成此操作)
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>();