asp.net-mvc – 在使用WEB API时,如何从POST中提取HttpResponseMessage中的内容?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 在使用WEB API时,如何从POST中提取HttpResponseMessage中的内容?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一个非常典型的CRUD操作将导致一个对象的Id设置一旦持久化。

所以,如果我在接受一个对象的控制器上有Post方法(JSON序列化,比方说)并返回一个HttpResponseMessage,其中HttpStatusCode Created和Content设置为同一个对象,Id从null更新为整数,那么我如何使用HttpClient获取在那个Id值?

它可能很简单,但我看到的只是System.Net.Http.StreamContent。从post方法返回Int更好吗?

谢谢。

更新(以下回答):

一个工作的例子……

  1. namespace TryWebAPI.Models {
  2. public class YouAreJoking {
  3. public int? Id { get; set; }
  4. public string ReallyRequiresFourPointFive { get; set; }
  5. }
  6. }
  7.  
  8. namespace TryWebAPI.Controllers {
  9. public class RyeController : ApiController {
  10. public HttpResponseMessage Post([FromBody] YouAreJoking value) {
  11. //Patience simulated
  12. value.Id = 42;
  13.  
  14. return new HttpResponseMessage(HttpStatusCode.Created) {
  15. Content = new ObjectContent<YouAreJoking>(value,new JsonMediaTypeFormatter(),new MediaTypeWithQualityHeaderValue("application/json"))
  16. };
  17. }
  18. }
  19. }
  20.  
  21. namespace TryWebApiClient {
  22. internal class Program {
  23. private static void Main(string[] args) {
  24. var result = CreateHumour();
  25. Console.WriteLine(result.Id);
  26. Console.ReadLine();
  27. }
  28.  
  29. private static YouAreJoking CreateHumour() {
  30. var client = new HttpClient();
  31. var pennyDropsFinally = new YouAreJoking { ReallyRequiresFourPointFive = "yes",Id = null };
  32.  
  33. YouAreJoking iGetItNow = null;
  34. var result = client
  35. .PostAsJsonAsync("http://localhost:1326/api/rye",pennyDropsFinally)
  36. .ContinueWith(x => {
  37. var response = x.Result;
  38. var getResponseTask = response
  39. .Content
  40. .ReadAsAsync<YouAreJoking>()
  41. .ContinueWith<YouAreJoking>(t => {
  42. iGetItNow = t.Result;
  43. return iGetItNow;
  44. }
  45. );
  46.  
  47. Task.WaitAll(getResponseTask);
  48. return x.Result;
  49. });
  50.  
  51. Task.WaitAll(result);
  52. return iGetItNow;
  53. }
  54. }
  55. }

似乎Node.js受到启发。

@R_404_323@

您可以使用ReadAsAsync< T>

.NET 4(你可以在没有延续的情况下做到这一点)

  1. var resultTask = client.PostAsJsonAsync<MyObject>("http://localhost/api/service",new MyObject()).ContinueWith<HttpResponseMessage>(t => {
  2. var response = t.Result;
  3. var objectTask = response.Content.ReadAsAsync<MyObject>().ContinueWith<Url>(u => {
  4. var myobject = u.Result;
  5. //do stuff
  6. });
  7. });

.NET 4.5

  1. var response = await client.PostAsJsonAsync<MyObject>("http://localhost/api/service",new MyObject());
  2. var myobject = await response.Content.ReadAsAsync<MyObject>();

猜你在找的asp.Net相关文章