【问题标题】:C# Rest api - post list object is always nullC# Rest api - 发布列表对象始终为空
【发布时间】:2021-06-15 03:41:11
【问题描述】:

我正在使用此代码将一些对象发布到我的 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();
    }
} 

当发布一个简单的对象时,代码可以正常工作:

[Route("api/Name/{ActivationKey}")]
public async Task<HttpResponseMessage> Post([FromBody] SomeKindOfObject value, string ActivationKey)
{
    Some code...
}

但是当我尝试发布同一对象的列表时,我在控制器中得到null

[Route("api/Name/{ActivationKey}")]
public async Task<HttpResponseMessage> Post([FromBody] List<SomeKindOfObject> value, string ActivationKey)
{
    Value is always null.
}

这是什么原因造成的,我该如何解决?

【问题讨论】:

    标签: c# asp.net-mvc api rest http-post


    【解决方案1】:

    试试

    public async Task<HttpResponseMessage> Post([FromBody] SomeKindOfObject[] value, string ActivationKey)
    

    反序列化可能与其目标容器类型相反,即。列表 vs 数组 vs 集合。

    【讨论】:

      【解决方案2】:

      显然问题是我尝试发布的列表太大(超过 15k 行),我所做的是将列表拆分为较短的列表并单独发布每个部分并且它有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        • 2011-08-28
        • 1970-01-01
        • 2018-12-26
        • 2014-05-09
        相关资源
        最近更新 更多