WebApi 接口参数传参详解

下面通过几个示例看看我们的get请求参数传递。

get请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),而post请求则是放在http协议包的包体中。

1.基础类型参数

[HttpPost]
public bool SaveData([FromBody]string NAME)
{
     return true;
}
$.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        data: { "": "Jim" },
        success: function (data, status) {}
    });
2.实体类型参数
public class TB_CHARGING
    {
        /// 
        /// 主键Id
        /// 
        public string ID { get; set; }

        /// 
        /// 充电设备名称
        /// 
        public string NAME { get; set; }

        /// 
        /// 充电设备描述
        /// 
        public string DES { get; set; }

        /// 
        /// 创建时间
        /// 
        public DateTime CREATETIME { get; set; }
    }
[HttpPost]
        public bool SaveData(TB_CHARGING oData)
        {
            return true;
        }
$.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        contentType: 'application/json',
        data: JSON.stringify({ NAME: "Jim",DES:"备注" }),
        success: function (data, status) {}
    });
3.实体集合
var arr = [
        { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },
        { ID: "2", NAME: "Lilei", CREATETIME: "1990-12-11" },
        { ID: "3", NAME: "Lucy", CREATETIME: "1986-01-10" }
    ];
    $.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        contentType: 'application/json',
        data: JSON.stringify(arr),
        success: function (data, status) {}
    });
[HttpPost]
        public bool SaveData(List lstCharging)
        {
            return true;
        }

4.后台发送请求参数的传递
public void TestReques()
    {
         //请求路径
            string url = "http://localhost:27221/api/Charging/SaveData";

            //定义request并设置request的路径
            WebRequest request = WebRequest.Create(url);
            request.Method = "post";

            //初始化request参数
            string postData = "{ ID: \"1\", NAME: \"Jim\", CREATETIME: \"1988-09-11\" }";

            //设置参数的编码格式,解决中文乱码
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //设置request的MIME类型及内容长度
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;

            //打开request字符流
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //定义response为前面的request响应
            WebResponse response = request.GetResponse();

            //获取相应的状态代码
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            //定义response字符流
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();//读取所有
            Console.WriteLine(responseFromServer);
    }


你可能感兴趣的:(.Net,前端开发)