使用WEB API时,如何从POST中提取HttpResponseMessage中的内容?

时间:2012-09-13 19:18:36

标签: asp.net-mvc serialization asp.net-web-api json.net

一个非常典型的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受到启发。

1 个答案:

答案 0 :(得分:48)

您可以使用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>();