[英]C# Rest api - post list object is always null
I'm using this code to post some object to my Rest API:我正在使用此代码将一些 object 发布到我的 Rest API:
public static string Post<T>(string uri, T data, string contentType = "application/json", string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
string str = JsonConvert.SerializeObject(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;
using (Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
and the code works just fine when posting a simple object:当发布一个简单的 object 时,代码工作得很好:
[Route("api/Name/{ActivationKey}")]
public async Task<HttpResponseMessage> Post([FromBody] SomeKindOfObject value, string ActivationKey)
{
Some code...
}
But when I try posting a list of the same object I get null
in the controller:但是,当我尝试发布相同 object 的列表时,我在null
中得到 null:
[Route("api/Name/{ActivationKey}")]
public async Task<HttpResponseMessage> Post([FromBody] List<SomeKindOfObject> value, string ActivationKey)
{
Value is always null.
}
What could cause this and how can I fix it?什么可能导致这种情况,我该如何解决?
Try尝试
public async Task<HttpResponseMessage> Post([FromBody] SomeKindOfObject[] value, string ActivationKey)
Desererialization can be contrary about its target container types, ie.反序列化可能与其目标容器类型相反,即。 list vs array vs collection.列表 vs 数组 vs 集合。
Apparently the problem was that the list I tried to post was too big (more than 15k rows), what I did is splitting the list to shorter lists and posted every part alone and it worked.显然问题是我尝试发布的列表太大(超过 15k 行),我所做的是将列表拆分为较短的列表并单独发布每个部分并且它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.