簡體   English   中英

400(錯誤請求)同時將 json 發送到 .net 6 Web ZDB974238714CA8DE6FZACE7

[英]400 (Bad Request) while sending json to .net 6 Web API

我正在嘗試將數據從 winform datagridview 發送到 webapi,所以我將 datagridview 轉換為 json。 在發送 json 時,它無法 POST 數據並發送此錯誤:

發生一個或多個驗證錯誤。","status":400,"traceId":"00-76f7972fcf00afc89a7f164ca37ee7ab-5198bf8e30719871-00","errors":{"$":["JSON 值無法轉換為 LabDatapi.模型.LabData

代碼:

public class LabData
    {
        public int SerialNumber { get; set; }
        public string LabParameterName { get; set; }
        public decimal LabValue { get; set; }
        public DateTime LabDate { get; set; }
    }

private void button2_Click(object sender, EventArgs e)
            {
                var url = "https://localhost:7248/api/Lab";
                dataGridView1.DataSource = LabResult.GetLabData();     
                var table = JsonConvert.SerializeObject(dataGridView1.DataSource);
                ApiSender apiSender = new ApiSender();
                apiSender.POSTData(table, url);
            }

public class ApiSender
    {
        private static HttpClient _httpClient = new HttpClient();

        public bool POSTData(object json, string url)
        {
            using (var content = new StringContent(JsonConvert.SerializeObject(json), System.Text.Encoding.UTF8, "application/json"))
            {
                HttpResponseMessage result = _httpClient.PostAsync(url, content).Result;
                if (result.StatusCode == System.Net.HttpStatusCode.Created)
                    return true;
                string returnValue = result.Content.ReadAsStringAsync().Result;
                throw new Exception($"Failed to POST data: ({result.StatusCode}): {returnValue}");
            }
        }
    }

接收Json數據格式

[{"SerialNumber":1,"LabParameterName":"abc","LabValue":7.80,"LabDate":"2001-11-16T10:10:00"},{"SerialNumber":2,"LabParameterName": "xyz","LabValue":10.00,"LabDate":"2001-11-16T10:10:00"},{"SerialNumber":3,"LabParameterName":"qq","LabValue":5.00,"LabDate ":"2001-03-16T10:10:00"},{"SerialNumber":18,"LabParameterName":"cbc","LabValue":200.0,"LabDate":"2001-11-16T10:10:00 "}]

The JSON value could not be converted to LabDataApi.Models.LabData

好吧,您正在嘗試將LabData數組轉換為LabData model。 更新 API 以接收IEnumerable<LabData> ,或更新客戶端以發送多個POST請求(針對每個LabData條目(不推薦))。

至少這就是你所問問題的答案——看起來你已經切斷了異常的結尾,也許你錯誤地省略了一些重要的細節?

轉換為 json 時,您的對象定義存在問題。 此外,您還需要將其作為列表或數組來獲取。

您的序列化/反序列化將更好地處理這些對象。

public class LabDatas
{
    public LabData[] Value { get; set; }
}

//or if you want list
public class LabDatas
{
    public List<LabData> Value { get; set; }
}

public class LabData
{
    public int SerialNumber { get; set; }
    public string LabParameterName { get; set; }
    public float LabValue { get; set; }
    public DateTime LabDate { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM