curl在POST请求时向webapi发送空数据

本文关键字:数据 webapi POST 请求 curl | 更新日期: 2023-09-27 18:20:25

我想通过curl windows 64位将数据POST到asp.net web api上(使用C#)。然而,每次我这样做时,控件都会传递给HttpPost方法,但是接受参数的值仍然为null。这在浏览器上使用url时不需要卷曲。。所以数据库没有问题。

我的curl语法是:

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

我的web api服务器端代码是

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

curl在POST请求时向webapi发送空数据

这是由于cmd.exe在Windows上使用curl时如何处理引号。

将命令更改为仅使用双引号,并转义JSON数据中的所有双引号。

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