如何将数组的对象传递给c#web服务

时间:2018-03-13 02:42:59

标签: c# json asp.net-web-api

我需要将这个json正文传递给我的web api post函数。

{
    "image_list":[
        {
            "image_name":"sample 1",
            "image_url":"url1",
            "image_description":"desc1"
        },
        {
            "image_name":"sample 2",
            "image_url":"url2",
            "image_description":"desc2"
        }
    ]
}

我应该在c#中使用哪种数据类型? 它应该在我的模型类中声明为列表吗? 下面是json传递的函数

   [Route("api/product/create")]
   [HttpPost]
   public HttpResponseMessage CreateProduct([FromBody]ProductModel product)
   {

        String product_id;
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[connection_string].ConnectionString))
        {

            SqlCommand cmd = new SqlCommand("sp_create_product", con);

            // I WANT TO PASS THAT ARRAY OF OBJECTS TO MY STORED PROC HERE
            cmd.Parameters.AddWithValue("product_image_array", product.image_list);

            SqlParameter outputParameter = new SqlParameter();
            outputParameter.ParameterName = "@product_id";
            outputParameter.SqlDbType = SqlDbType.Int;
            outputParameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(outputParameter);

            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();
            cmd.ExecuteNonQuery();

            product_id = outputParameter.Value.ToString();
        }

        var message = Request.CreateResponse(HttpStatusCode.OK, product_id);
        return message;
    }

1 个答案:

答案 0 :(得分:2)

您可以使用此ProductModel来接收您的json数据。

public class ImageList
{
    public string image_name { get; set; }
    public string image_url { get; set; }
    public string image_description { get; set; }
}

public class ProductModel 
{
    public List<ImageList> image_list { get; set; }
}