HttpClient PostAsync发布空内容 [英] HttpClient PostAsync posting null content
问题描述
我有一个api调用了另一个.
I have one api calling another.
这是我的代码,似乎在世界的另一端导致了ModelState.IsValid = false
.
and here is my code which seems to cause ModelState.IsValid = false
on the other side of world.
var baseUri = new Uri("http://localhost:5001/"):
_httpClient.BaseAdress = baseUri;
var data = new StringContent(content: model.Tostring(),
encoding: Encoding.UTF8,
mediaType: "application/json");
var response = await _httpClient.PostAsync("api/product", data);
在被称为api上观看Post([FromBody]Product product)
,我只看到product=null
.
watching Post([FromBody]Product product)
on the api being called I just see product=null
.
更改为Post([FromBody]object product)
也会显示null
.
从Postman
调用api可以很好地工作.将我的问题本地化为PostAsync
.我的PostAsync
怎么了?
calling the api from Postman
works perfectly fine. which localize my problem to PostAsync
. what's going on with my PostAsync
?
修改:
我知道人们可能会建议PostAsJsonAsync
,但是只有在我知道PostAsync
有什么问题之后,我才会尝试. :(
I know people might suggest PostAsJsonAsync
, but I'll try it only after I know what's the problem with PostAsync
. :(
推荐答案
如注释中所述,当您调用model.ToString
时,model
并未转换为JSON.您最终发现可以使用Json.Net使用JsonConvert.SerializeObject(model)
将模型序列化为JSON.这将有助于将模型序列化为JSON.
As indicated in the comments the model
was not being converted to JSON when you called model.ToString
. You eventually figured out that you can use Json.Net to serialize the model to JSON with JsonConvert.SerializeObject(model)
. This will work for serializing the model to JSON.
您可以再走一步,创建一个扩展方法来为您执行该功能
You could go one step further and create an extension method to perform that functionality for you
public class JSONStringExtension {
public static string ToJsonString(this object model) {
if(model is string) throw new ArgumentException("mode should not be a string");
return JsonConvert.SerializeObject(model);
}
}
现在,这将允许您在模型上调用方法并将其隐式转换为代码中的JSON.
This will now allow you to call the method on your model and covert it to JSON in your code.
var baseUri = new Uri("http://localhost:5001/"):
_httpClient.BaseAdress = baseUri;
var data = new StringContent(content: model.ToJsonString(), //<--Extension method here
encoding: Encoding.UTF8,
mediaType: "application/json");
var response = await _httpClient.PostAsync("api/product", data);
经常使用的PostAsJsonAsync
扩展方法通过为您抽象JSON序列化步骤来实现最终实现的相同功能.在内部它调用相同的PostAsync
方法.
The PostAsJsonAsync
extension method that is frequently used basically performs the same thing you eventually realized by abstracting the JSON serialization step for you. internally it is calling the same PostAsync
method.
看起来会像这样
public static Task<HttpResponseMessage> PostAsJsonAsync(this HttpClient httpClient, string url, object content) {
var json = JsonConvert.SerializeObject(content)
var data = new StringContent(content: json,
encoding: Encoding.UTF8,
mediaType: "application/json");
return httpClient.PostAsync(url, data);
}
这篇关于HttpClient PostAsync发布空内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!