Adding a json body to a POST with WebRequest

Viewed 545

I am trying to POST some items through the body but I keep getting "(400) Bad Request" Which from what I could gather is usually an issue with the endpoint you are trying to hit. This is correct as I have tested it with simple calls.

This is my first time trying to make a POST this way with a body so I'm not sure what I am missing or doing wrong.

This is the endpoint I'm trying to hit

[Route("api/[controller]")]
   [ApiController]
   public class SaleController : ControllerBase
   {
       [HttpPost]
       [Route("[action]")]
       [Route("Sale/Test")]
       public string Test([FromBody] Inventory[] inventories)
       {
           return "Found me";
       }
}

It pops the err 400 at the httpResponse


   public IEnumerable<Inventory> GetTest(IpPartial ipPartial, Inventory[] inventories)
        {
            WebRequest request = WebRequest.Create("http://localhost:5002/api/Sale/Test");
            request.Method = "POST";
            request.ContentType = "application/json";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string jsonString = new JavaScriptSerializer().Serialize(inventories);

                streamWriter.Write(jsonString);
                var httpResponse = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    var pass = result.ToString();
                }
                streamWriter.Flush();
                streamWriter.Close();
            }

            return inventories;
        }

This is just a simplified idea of what I'm trying to pass

[
    {
        "id": 1,
        "categoryId": 1,
        "taxId": 1,
        "unitId": 1,
        "scheduleId": 0,
        "description": "Konsultasie",
        "code": ""
    },
    {
        "id": 2,
        "categoryId": 7,
        "taxId": 1,
        "unitId": 1,
        "scheduleId": 10,
        "description": "Laxapet 50g",
        "code": "220L"     
    }
]
1 Answers

Solved it by just swapping to a simple async call.

public async Task<IEnumerable<Inventory>> CreateSale(IpPartial ipPartial, Inventory[] inventories)
        {
            string jsonString = new JavaScriptSerializer().Serialize(inventories);
            var data = new StringContent(jsonString, Encoding.UTF8, "application/json");
            var url = "http://localhost:5002/api/Sale/CreateSales";
            using var client = new HttpClient();
            var response = await client.PostAsync(url, data);
            string result = response.Content.ReadAsStringAsync().Result;

            return inventories;
            
        }
Related