webapi-2 接口参数
1. 实例
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using wxweb.Areas.API.Models; namespace wxweb.Areas.API.Controllers { public class ProductController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; Product[] products_post = new Product[] { new Product { Id = 1, Name = "name01", Category = "Category01", Price = 10 }, new Product { Id = 2, Name = "name02", Category = "Category02", Price = 20M }, new Product { Id = 3, Name = "name03", Category = "Category03", Price = 30M } }; /// <summary> /// get 无参数传参 /// </summary> /// <returns></returns> [HttpGet] public IEnumerable<Product> GetAllProducts() { return products; } /// <summary> /// get 单参数传参 /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("api/Product/GetProductById")] [HttpGet] public IHttpActionResult GetProductById(string id) { var product = products.FirstOrDefault((p) => p.Id == Convert.ToInt32(id)); if (product == null) { return NotFound(); } return Ok(product); } /// <summary> /// get多参数传参 /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <returns></returns> [HttpGet] public string para_get_base(string id,string name) { return "id:"+id+" name:"+name; } /// <summary> /// get form传参 /// </summary> /// <param name="p"></param> /// <returns></returns> [Route("api/Product/para_get_form")] [HttpGet] public string para_get_form([FromUri]Product p) { return "p.Name:" + p.Name + " p.Price:" + p.Price; } /// <summary> /// post 无参数传参 /// </summary> /// <returns></returns> [Route("api/Product/GetProducts")] [HttpPost] public IEnumerable<Product> GetProducts() { return products_post; } /// <summary> /// post 单个参数传参 /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("api/Product/GetProduct")] [HttpPost] public IHttpActionResult GetProduct([FromBody]string id) { var product = products_post.FirstOrDefault((p) => p.Id ==Convert.ToInt32( id)); if (product == null) { return NotFound(); } return Ok(product); } /// <summary> /// post 多参数传参 /// </summary> /// <param name="obj"></param> /// <returns></returns> [Route("api/Product/para_post_base")] [HttpPost] public string para_post_base(dynamic obj) { string id = obj["id"].ToString(); string name = obj["name"].ToString(); return "id:" + id + " name:" + name; } /// <summary> /// post form传参 /// </summary> /// <param name="p"></param> /// <returns></returns> [Route("api/Product/para_post_form")] [HttpPost] public string para_post_form(Product p) { return "p.Name:" + p.Name + " p.Price:" + p.Price; } /// <summary> /// post base+form传参 /// </summary> /// <param name="p"></param> /// <returns></returns> [Route("api/Product/para_post_baseform")] [HttpPost] public string para_post_baseform(dynamic obj) { var parapost = Convert.ToString(obj.parapost); Product p = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(Convert.ToString(obj.formdata)); return "parapost:"+parapost+ " p.Name:" + p.Name + " p.Price:" + p.Price; } /// <summary> /// post 数组参数 /// </summary> /// <param name="ids"></param> /// <returns></returns> [Route("api/Product/post_array")] [HttpPost] public string post_array(string[] ids) { string result = ""; for (int i = 0; i < ids.Length; i++) { result += " :" + ids[i]; } return result; } /// <summary> /// post 实体数组参数 /// </summary> /// <param name="ids"></param> /// <returns></returns> [Route("api/Product/post_ojblist")] [HttpPost] public string post_ojblist(List<Product> plist) { string result = ""; for (int i = 0; i < plist.Count; i++) { result +=" <br/>||"+i+ ":name:" + plist[i].Name+" price:"+plist[i].Price; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace wxweb.Areas.API.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Product App</title> </head> <body> <div> <h2>All Products from get Method</h2> <ul id="products" /> </div> <div> <h2>Search by ID from get Method</h2> <input type="text" id="prodId" size="5" /> <input type="button" value="Search" onclick="find();" /> <p id="product" /> </div> <div style="border-top:1px solid #ccc;"> <h2>All Products from post Method</h2> <ul id="products_post" /> </div> <div> <h2>Search by ID from post Method</h2> <input type="text" id="prodId_post" size="5" /> <input type="button" value="Search" onclick="findpost();" /> <p id="product_post" /> </div> <div style="border-top:2px solid #ccc;"> <h3>多参数传参</h3> id:<input type="text" id="get_id" name="=get_id" /><br /> name:<input type="text" id="get_name" name="=get_name" /><br /> <input type="button" value="get传参" onclick="para_get_base()" /><br /> <span>get方式api调用结果</span> <span id="get_result"></span><br /> <input type="button" value="post传参" onclick="para_post_base()" /><br /> <span>post方式api调用结果</span><span id="get_result_post"></span><br /> </div> <div style="border-top:2px solid #ccc;"> <h3>实体传参</h3> <form id="form1"> base:<input type="text" id="parapost"><br /> Id:<input type="text" id="Id" name="Id" /><br /> Name:<input type="text" id="Name" name="Name" /><br /> Category:<input type="text" id="Category" name="Category" /><br /> Price:<input type="number" id="Price" name="Price" /><br /> </form> <input type="button" value="get form传参" onclick="para_get_form()" /><br /> <span>get方式api调用结果</span> <span id="get_result_form"></span><br /> <input type="button" value="post form传参" onclick="para_post_form()" /><br /> <span>post方式api调用结果</span> <span id="get_result_form_post"></span><br /> <input type="button" value="post base+form传参" onclick="para_post_baseform()" /><br /> <span>post base+form方式api调用结果</span> <span id="get_result_baseform_post"></span><br /> </div> <div style="border-top:2px solid #ccc;"> <h3>数组传参</h3> <input type="button" value="post数组传参" onclick="post_array()" /><br /> <span>post方式api调用结果</span><span id="post_array"></span><br /> </div> <div style="border-top:2px solid #ccc;"> <h3>实体集合</h3> <input type="button" value="post实体集合" onclick="post_ojblist()" /><br /> <span>post方式api调用结果</span><span id="post_ojblist"></span><br /> </div> <div style="margin-bottom:100px;"></div> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script> <script src="../Scripts/jquery.serializeObject.js"></script> <script type="text/javascript"> $(document).ready(function () { var uri = '/api/Product'; var para = ''; //get方式获取 $.get(uri, para, function (data) { $.each(data, function (key, item) { $('<li>', { text: formatItem(item) }).appendTo($('#products')); }); }) var uripost = '/api/Product/GetProducts'; //post方式获取 $.post(uripost, para, function (data) { $.each(data, function (key, item) { $('<li>', { text: formatItem(item) }).appendTo($('#products_post')); }); }) }); function formatItem(item) { return item.Name + ': $' + item.Price; } //使用get方式 单参数查询 function find() { var uri = '/api/Product/GetProductById'; var id = $('#prodId').val(); var para = { 'id': id }; //var uri = ''; $.get(uri, para, function (data) { $('#product').text(formatItem(data)); }) } //使用post方式 单参数查询 function findpost() { var uri = '/api/Product/GetProduct'; var id = $('#prodId_post').val(); var para = { '': id };//注意传递参数的参数名称,填'' //var uri = ''; $.post(uri, para, function (data) { $('#product_post').text(formatItem(data)); }) } //get方式多参数传参 function para_get_base() { var uri = '/api/Product'; var id = $('#get_id').val(); var name = $('#get_name').val(); var para = { id: id, name: name }; $.ajax({ url: uri, type: 'get', async: true, data: para, dataType: 'text', success: function (r) { $('#get_result').html(r); }, error: function (r) { console.log(r); } }); } //post方式多参数传参 function para_post_base() { var uri = '/api/Product/para_post_base'; var id = $('#get_id').val(); var name = $('#get_name').val(); var para = { id: id, name: name }; para = JSON.stringify(para);//js对象转化为字符传递 $.ajax({ url: uri, type: 'post', async: true, data: para, dataType: 'text', contentType: "application/json", success: function (r) { $('#get_result_post').html(r); }, error: function (r) { console.log(r); } }); } //get方式传递form参数 function para_get_form() { var uri = '/api/Product/para_get_form'; //参数方式1,借助serializeObject 将form序列化为json对象 var para = $('#form1').serializeObject(); //参数方式2,依次写出每一个参数值 var para2 = { Id: $('#Id').val(), Name: $('#Name').val(), Category: $('#Category').val(), Price: $('#Price').val() };//参数方式2, $.ajax({ url: uri, type: 'get', async: true, data: para, contentType: "application/json", dataType: 'text', success: function (r) { $('#get_result_form').html(r); }, error: function (r) { alert(r); } }); } //post方式传递form参数 function para_post_form() { var uri = '/api/Product/para_post_form'; //参数方式1,借助serializeObject 将form序列化为json对象 var para = $('#form1').serializeObject(); //参数方式2,依次写出每一个参数值 var para2 = { Id: $('#Id').val(), Name: $('#Name').val(), Category: $('#Category').val(), Price: $('#Price').val() };//参数方式2, $.ajax({ url: uri, type: 'post', async: true, data: para, dataType: 'text', success: function (r) { $('#get_result_form_post').html(r); }, error: function (r) { alert(r); } }); } //post方式传递form参数 function para_post_baseform() { var uri = '/api/Product/para_post_baseform'; //参数方式1,借助serializeObject 将form序列化为json对象 var formdata = $('#form1').serializeObject(); var para = JSON.stringify({ parapost: $('#parapost').val(), formdata: formdata }) $.ajax({ url: uri, type: 'post', async: true, data: para, dataType: 'text', contentType: "application/json", success: function (r) { $('#get_result_baseform_post').html(r); }, error: function (r) { alert(r); } }); } function post_array() { var arr = ["1", "2", "3", "4"]; var para = JSON.stringify(arr); var uri = '/api/Product/post_array'; $.ajax({ type: "post", url: uri, contentType: 'application/json', data: para, dataType: 'text', success: function (data) { $('#post_array').html(data); }, error: function (data) { console.log(data); } }); } function post_ojblist() { var arr = [ { Id: 1, Name: "Jim", Category: "001", Price:10 }, { Id: 2, Name: "jack", Category: "002", Price: 20 }, { Id: 3, Name: "tom", Category: "003", Price: 30 } ]; var para = JSON.stringify(arr); var uri = '/api/Product/post_ojblist'; $.ajax({ type: "post", url: uri, contentType: 'application/json', data: para, dataType: 'text', success: function (data, status) { if (status) { $('#post_ojblist').html(data); } else { console.log(data); } }, error: function (data) { console.log(data); } }); } </script> </body> </html>
//
// Use internal $.serializeArray to get list of form elements which is
// consistent with $.serialize
//
// From version 2.0.0, $.serializeObject will stop converting [name] values
// to camelCase format. This is *consistent* with other serialize methods:
//
// - $.serialize
// - $.serializeArray
//
// If you require camel casing, you can either download version 1.0.4 or map
// them yourself.
//
(function($){
$.fn.serializeObject = function () {
"use strict";
var result = {};
var extend = function (i, element) {
var node = result[element.name];
// If node with same name exists already, need to convert it to an array as it
// is a multi-value field (i.e., checkboxes)
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};
$.each(this.serializeArray(), extend);
return result;
};
})(jQuery);
2. get 请求
1>:实体作为参数调用时,前台的实体参数无法直接传递到后台,需在webapi中对实体参数加上[FromUri]特性说明。
这是因为通过get方式传递的参数都是通过Request URL传递到后台的,则FromUri 给api说明 参数是从Request URL中获取到的。
如下:
/// <summary> /// get form传参 /// </summary> /// <param name="p"></param> /// <returns></returns> [Route("api/Product/para_get_form")] [HttpGet] public string para_get_form([FromUri]Product p) { return "p.Name:" + p.Name + " p.Price:" + p.Price; }
//get方式传递form参数
function para_get_form() {
var uri = '/api/Product/para_get_form';
//参数方式1,借助serializeObject 将form序列化为json对象
var para = $('#form1').serializeObject();
//参数方式2,依次写出每一个参数值
var para2 = { Id: $('#Id').val(), Name: $('#Name').val(), Category: $('#Category').val(), Price: $('#Price').val() };//参数方式2,
$.ajax({
url: uri,
type: 'get',
async: true,
data: para,
contentType: "application/json",
dataType: 'text',
success: function (r) {
$('#get_result_form').html(r);
}, error: function (r) {
alert(r);
}
});
}
2> 如果不想通过[FromUri]特性说明的方式进行传递实体,也可以使用把实体先序列化在反序列化的方式传递。
$.ajax({ type: "get", url: "http://localhost:27221/api/Charging/GetByModel", contentType: "application/json", data: { strQuery: JSON.stringify({ ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" }) }, success: function (data, status) { if (status == "success") { $("#div_test").html(data); } } }); [HttpGet] public string GetByModel(string strQuery) { TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(strQuery); return "ChargingData" + oData.ID; }
get 方式总结
(1)Get参数传递的本质是url字符串拼接;
(2)url字符串长度受限制;
(3)Get参数传递在Http请求头部传递,而不支持Request-Body传递;
(4)Get类型的方法支持参数为基本类型,不支持实体类型;
(5)Get类型的方法命名,应尽量采用“Get+方法名”的命名方式,且习惯性地在方法前加上[HttpGet特性];
(6)实参与形参的匹配,遵循路由规则;
(7)Get对应DB的Select操作,从这一点来理解,就知道为什么Http不支持实体对象传递的合理性了,因为一般情况,我们都是通过简单的字段查询信息(对应基本类型),
如ID号,用户名等,而不会通过一个实体查询数据;
3 post 请求
1> post 单参数请求
我们一般的通过url取参数的机制是键值对,即某一个key等于某一个value,而这里的FromBody和我们一般通过url取参数的机制则不同,它的机制是=value,没有key的概念,并且如果你写了key(比如你的ajax参数写的{id:"1"}),后台反而得到的id等于null。
//使用post方式 单参数查询 function findpost() { var uri = '/api/Product/GetProduct'; var id = $('#prodId_post').val(); var para = { '': id };//注意传递参数的参数名称,填'' //var uri = ''; $.post(uri, para, function (data) { $('#product_post').text(formatItem(data)); }) } /// <summary> /// post 单个参数传参 /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("api/Product/GetProduct")] [HttpPost] public IHttpActionResult GetProduct([FromBody]string id) { var product = products_post.FirstOrDefault((p) => p.Id ==Convert.ToInt32( id)); if (product == null) { return NotFound(); } return Ok(product); }
2> 多参数请求
post方式是不支持多参数方式请求的,为了传递多参数我们可以采用其他的方式。
比如,在后台建立对象实体,然后将整个实体作为对象传递,
//post方式传递form参数 function para_post_form() { var uri = '/api/Product/para_post_form'; //参数方式1,借助serializeObject 将form序列化为json对象 var para = $('#form1').serializeObject(); //参数方式2,依次写出每一个参数值 var para2 = { Id: $('#Id').val(), Name: $('#Name').val(), Category: $('#Category').val(), Price: $('#Price').val() };//参数方式2, $.ajax({ url: uri, type: 'post', async: true, data: para, dataType: 'text', success: function (r) { $('#get_result_form_post').html(r); }, error: function (r) { alert(r); } }); } /// <summary> /// post form传参 /// </summary> /// <param name="p"></param> /// <returns></returns> [Route("api/Product/para_post_form")] [HttpPost] public string para_post_form(Product p) { return "p.Name:" + p.Name + " p.Price:" + p.Price; }
html页面中如果使用form序列化的方式,可以调用serializeObject.js的方法得到json对象。
比如,使用dynamic参数,动态的获取所需要的参数。
//post方式多参数传参 function para_post_base() { var uri = '/api/Product/para_post_base'; var id = $('#get_id').val(); var name = $('#get_name').val(); var para = { id: id, name: name }; para = JSON.stringify(para);//js对象转化为字符传递 $.ajax({ url: uri, type: 'post', async: true, data: para, dataType: 'text', contentType: "application/json", success: function (r) { $('#get_result_post').html(r); }, error: function (r) { console.log(r); } }); } /// <summary> /// post 多参数传参 /// </summary> /// <param name="obj"></param> /// <returns></returns> [Route("api/Product/para_post_base")] [HttpPost] public string para_post_base(dynamic obj) { string id = obj["id"].ToString(); string name = obj["name"].ToString(); return "id:" + id + " name:" + name; }
post 方式总结
(1)Post参数传递本身是在Request-Body内传递,而Get参数传递本质是url拼接;
(2)Post参数传递不是key/value形式,而Get参数是key/value形式;
(3)Post传递参数时,无论是单个参数还是对象,均借助[FromBody]特性(当然,某些情况去掉[FromBody]特性也可把值传递进去,但为了规范化,尽量加上该特性);
(4)Post没长度限制,而Get有长度限制(一般为1024b);
(5)Post相对Get,较安全;
(6)Post操作相当于DB的Insert操作;
4 总结
1.虽然HTTP请求方法有20多种,常用的大致为4种,即Get,Post,Put,Delete(当然,像Trace,Head等也常用);
2.Get,Post,Put,Delete分别对应DB的Select,Insert,Update和Delete操作;
3.WebApi参数类型,大致分为基本数据类类型和对象数据类型(当然你也可以理解为抽象数据类型);
4.研究WebApi参数传递,只需研究Get和Post即可,因为其他http方法参数传递基本都是有这两种组合而成(如Put有Get和Post组合而成),或者相似(如Delete与Get相似);
5.对于控制器方法,尽量参照规范格式写,如在相应控制器方法上加上对应的htt请求(Get对应[HttpGet],Post对应[HttpPost]),方法名尽量采用“Http请类型+方法名”格式(如Get请求,建议采用Get+MethodName;Post请求对应Post+MethodName);
6.WebApi参数请求,大致分为两大类型,即Request-url和Request-body;
引用:
https://www.cnblogs.com/landeanfen/p/5337072.html#_label3
http://www.cnblogs.com/wangjiming/p/8378108.html