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

When I Post this Data Throw Postman To Web API((http://192.168.18.15/api/PostData)) it works for me and gives me 200 OK Success CODE Method: 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"
 }
]
}
]

Now I want to Implement C# Code to Post this JSON data and I tried this Code:

  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;
}

it gives me an error Message: Wrong Attempt Status Code:400 Error: UnAuthorized can anyone help me where is the Problems my Token is Correct why it give that Error thanks



Solution 1:[1]

your model should be a collection, since you are using collection for postman. Try this model

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

and try to add a content type

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1