lea*_*ner 5 c# asp.net-web-api
我想通过 curl windows 64 位将数据发布到 asp.net web api(using C#) 上。但是,每次我这样做时,控制都会传递给 HttpPost 方法,但是接受参数的值仍然为空。这在浏览器上使用 url 时无需 curl 即可工作..所以数据库没有问题。
我的卷曲语法是:
curl -X POST 'Content-Type:application/json' --data '[{"Id":"44","Name":"Abc","Category":"xyz","Price":"98"}]' "http://example.com/Post/Products"
Run Code Online (Sandbox Code Playgroud)
我的 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;
}
Run Code Online (Sandbox Code Playgroud)
这是由于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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2219 次 |
| 最近记录: |