gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:34:10 24 4
gpt4 key购买 nike

相当典型的CRUD操作将导致对象的ID设置一旦持久化。

因此,如果我在 Controller 上有Post方法,该方法接受一个对象(说是JSON序列化),并返回一个HttpStatsCode Created和Content设置为同一对象的HttpResponseMessage,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受到了启发。

最佳答案

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

关于asp.net-mvc - 使用WEB API时,如何从POST的HttpResponseMessage中提取内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com