Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

curl sending null data on POST request to web api

I want to POST data through curl windows 64 bits onto a asp.net web api(using C#) . However every tim i do so, the control passes to the HttpPost method however the values of the accepting parameter remains null. This works without curl on using url on browser..so no problem with database.

My curl syntax is:

curl -X POST 'Content-Type:application/json' --data '[{"Id":"44","Name":"Abc","Category":"xyz","Price":"98"}]' "http://example.com/Post/Products"

My server side code of web api is

[ActionName("Default Action")]
[Route("Post/Products")]
[AcceptVerbs("Get"), HttpPost]
public List<ProductDetails> PostProduct([FromBody] List<ProductDetails>  pro)
{
    // IEnumerable<string> headerValues = Request.Headers.GetValues("MyCustomID");
    // var ide = headerValues.FirstOrDefault();
    // int id=Convert.ToInt16(pro.Id);
    // int Pric = Convert.ToInt16(Pricc);
    con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\mydatabase.mdf;Integrated Security=True");
    SqlCommand ss = new SqlCommand("Insert into [Table] values ("+pro[0].Id+",'"+pro[0].Name+"','"+pro[0].Category+"',"+pro[0].Price+")", con);
    con.Open();
    SqlDataReader dr2 = ss.ExecuteReader();
    con.Close();
    con.Open();
    SqlCommand cmd=new SqlCommand ("select * from [Table]",con); 
    SqlDataReader dr1 = cmd.ExecuteReader();
    if (dr1.HasRows)
    {
        while (dr1.Read())
        {
            product1.Add(new ProductDetails() { Id = int.Parse(dr1[0].ToString()), Name = dr1[1].ToString(), Category = dr1[2].ToString(), Price = int.Parse(dr1[3].ToString()) });
        }
    }
    con.Close();

    if (ModelState.IsValid)
    {
        // var item = new pro { Id = id, Name = Nam, Category = Cate, Price = Pric };
        // products.Add(item);
        HttpResponseMessage response =Request.CreateResponse(HttpStatusCode.Created, product1);
        // response.Headers.Location = new Uri(Url.Link("DefaultApi1", new { id=item.Id }));               
    }
    return product1;
}
like image 291
learner Avatar asked Oct 31 '22 17:10

learner


1 Answers

This is due to how the quotes are handled by cmd.exe when using curl on Windows.

Change the command to use only double quotes and escape all of the ones in your JSON data.

curl -X POST "Content-Type:application/json" --data "[{\"Id\":\"44\",\"Name\":\"Abc\",\"Category\":\"xyz\",\"Price\":\"98\"}]" "http://example.com/Post/Products"
like image 126
Owen Pauling Avatar answered Nov 08 '22 06:11

Owen Pauling