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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12413287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:14:43  来源:igfitidea点击:

How do I extract content from HttpResponseMessage from POST when using WEB API?

asp.net-mvcserializationasp.net-web-apijson.net

提问by Kofi Sarfo

A pretty typical CRUD operation will result in an object having its Id set once persisted.

一个非常典型的 CRUD 操作将导致对象在持久化后设置其 Id。

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?

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

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?

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

Thanks.

谢谢。

Update (following answer):

更新(以下答案):

A working example...

一个工作示例...

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;
        }
    }
}

Seems Node.js inspired.

似乎受 Node.js 启发。

回答by Filip W

You can use ReadAsAsync<T>

您可以使用 ReadAsAsync<T>

.NET 4 (you can do that without continuations as well)

.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

.NET 4.5

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