如何使用Web API时,我从中提取了Htt $ P $从POST psponseMessage内容? [英] How do I extract content from HttpResponseMessage from POST when using WEB API?
问题描述
一个pretty典型的CRUD操作将导致有其ID为一次持续的对象。
A pretty typical CRUD operation will result in an object having its Id set once persisted.
所以,如果我有接受一个对象(JSON序列化,说的)并返回的Htt presponseMessage用的HTTPStatus code创建和内容设置与标识从空更新到同一个对象在控制器上Post方法一个整数,怎么做,然后我用的HttpClient来获得该标识的价值?
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?
这也许很简单,但我看到的是System.Net.Http.StreamContent。难道只是为了更好地从POST方法返回一个int?
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?
感谢。
更新(以下答案):
一个工作示例...
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的启发。
Seems Node.js inspired.
推荐答案
您可以使用 ReadAsAsync&LT; T&GT;
.NET 4(你可以做,没有延续以及)
.NET 4 (you can do that without continuations as well)
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
.NET 4.5
var response = await client.PostAsJsonAsync<MyObject>("http://localhost/api/service", new MyObject());
var myobject = await response.Content.ReadAsAsync<MyObject>();
这篇关于如何使用Web API时,我从中提取了Htt $ P $从POST psponseMessage内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!