Search code examples
c#apiasp.net-core-mvcwebapinewtons-method

Cannot convert Newtonsoft.Json.JsonConverter


public async Task<IActionResult> SiparisEkle(int userID, [FromQuery] int[] productIDs, [FromQuery] short[] quantities)
{
    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(userID, productIDs, quantities), Encoding.UTF8, "application/json");

        using (var cevap = await httpClient.PutAsync($"{uri}/api/Order/SiparisEkle", content))
        {
            string apiCevap = await cevap.Content.ReadAsStringAsync();

        }
    }
    return RedirectToAction("Index");
}

How can I go about fixing this error?

[HttpPost]
public async Task<IActionResult> SiparisEkle(int userID, [FromQuery] int[] productIDs, [FromQuery] short[] quantities)
{
    Order newOrder = new Order();
    newOrder.UserID = userID;
    newOrder.Status = Status.Pending;
    newOrder.isActive = true;


    using (var httpClient = new HttpClient())
    {
        StringContent content = new StringContent(JsonConvert.SerializeObject(newOrder), Encoding.UTF8, "application/json");

        using (var cevap = await httpClient.PutAsync($"{uri}/api/Order/SiparisEkle", content))
        {
            string apiCevap = await cevap.Content.ReadAsStringAsync();

        }
    }
    return RedirectToAction("Index");
}

This is how it is last. This is how I solved my problem


Solution

  • Have you tried instantiating the 'content' object on a separate line and then trying to set it, like so:

    StringContent content = new StringContent();
    content = JsonConvert.SerializeObject(userID, productIDs, quantities);
    

    Apologies if that's an unhelpful suggestion. I cannot see the StringContent class so I do not know if you need it in one due to a constructor in the class. For more help, here is the NewtonSoft documentation about Serializing and Deserializing. https://www.newtonsoft.com/json/help/html/SerializingJSON.htm#JsonSerializer