22

一个非常典型的 CRUD 操作将导致一个对象的 Id 设置一次。

因此,如果我在控制器上有 Post 方法,该方法接受一个对象(例如,JSON 序列化)并返回一个 HttpResponseMessage 并创建了 HttpStatusCode 并将 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 的启发。

4

1 回答 1

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>();
于 2012-09-13T19:50:49.747 回答