如何使用 c# WPF 在 Web API 中 Post 包含子详细信息的数据?

How to Post data with Subdetails in Web API using c# WPF?

当我 Post 此数据将 Postman To Web API((http://192.168.18.15/api/PostData)) 它对我有用并给了我 200 OK Success CODE 方法:POST, Headers: Content-Type: application/json, cache-control: no-cache

[
{
 "Code": "900350491",
"FullName":"John Setalh",
 "OrgCode": "13",
 "OrgDescription": "Microsoft Services",
 "RegCode": "11",
 "DISTRICT_CODE": "900",
 "ACCOUNT_NO": "00012043",
 "BANK_ACCOUNT_NO": "00003043",
 "DESCRIPTIONS": "just test the System",

 "AMOUNT": "300",
 "SUB_DETAILS":
[
{
 "Unit": "73000",
 "ReCode": "13300",
 "ReDes":"Some Description",
 "ReAmount": "0"
 }
]
}
]

现在我想对 Post 这个 JSON 数据实施 C# 代码,我尝试了这个代码:

  using (var client = new HttpClient())
            {
               
              client.DefaultRequestHeaders.Authorization =
              new AuthenticationHeaderValue("Bearer",mytoken);
                client.BaseAddress = new Uri("http://192.168.18.15/");
               MyModel r = new MyModel();
                r.Code = "12354";
                r.FullName = "FullName Here";
                r.OrgCode = "73";
                r.OrgDescription= "SomeDescription";
                r.RegCode = "50";
                r.DISTRICT_CODE = "230";
                r.ACCOUNT_NO = "00012043";
                r.BANK_ACCOUNT_NO = "00203043";
                r.DESCRIPTIONS = "just test the System";
                r.AMOUNT = "300";
                r.SUB_DETAILS.Unit="73000";
                r.SUB_DETAILS.ReCode="13300";
                r.SUB_DETAILS.ReDes="Some Description";
                r.SUB_DETAILS.ReAmount="300";
 var sendData = client.PostAsJsonAsync("api/PostData", new List<MyModel> {r}).Result;
                var result = sendData.Content.ReadAsStringAsync();
                string TariffNos = result.Result;
}

它给我一条错误消息:错误的尝试状态Code:400错误:未经授权 任何人都可以帮助我我的令牌的问题在哪里是正确的为什么它会给出那个错误 谢谢

你的模型应该是一个集合,因为你正在为邮递员使用集合。试试这个模型

 var sendData = client.PostAsJsonAsync("api/PostData", new List<MyModel> {r}).Result;

并尝试添加内容类型

var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);