android webapi,WebApi接口传参详解

本篇通过get、post、put、delete四种请求方式分别谈谈基础类型(包括int/string/datetime等)、实体、数组等类型的参数如何传递。

一、get请求

1、基础类型参数

[HttpGet]

public string GetAllChargingData(int id, string name)

{

return "ChargingData" + id;

}

$.ajax({

type: "get",

url: "http://localhost:27221/api/Charging/GetAllChargingData",

data: { id: 1, name: "Jim", bir: "1988-09-11"},

success: function (data, status) {

if (status == "success") {

$("#div_test").html(data);

}

}

});

2、实体作为参数

如果我们在get请求时想将实体对象做参数直接传递到后台,这样是不可行的。原来,get请求的时候,默认是将参数全部放到了url里面直接以string的形式传递的,后台自然接不到了。

正确传参方式:

$.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(strQuery);

return "ChargingData" + oData.ID;

}

3、数组作为参数

一般get请求不建议将数组作为参数,因为我们知道get请求传递参数的大小是有限制的,最大1024字节,数组里面内容较多时,将其作为参数传递可能会发生参数超限丢失的情况。

4、“怪异”的get请求

为什么会说get请求“怪异”呢?我们先来看看下面的两种写法对比。

(1)WebApi的方法名称以get开头

$.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(strQuery);

return "ChargingData" + oData.ID;

}

这是标准写法,后台加[HttpGet],参数正常得到。

为了对比,我将[HttpGet]去掉,然后再调用

//[HttpGet]

public string GetByModel(string strQuery)

{

TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject(strQuery);

return "ChargingData" + oData.ID;

}

貌似没有任何问题!有人就想,那是否所有的get请求都可以省略掉[HttpGet]这个标注呢。我们试试便知。

(2)WebApi的方法名称不以get开头

我们把之前的方法名由GetByModel改成FindByModel,这个再正常不过了,很多人查询就不想用Get开头,还有直接用Query开头的。这个有什么关系吗?

$.ajax({

type: "get",

url: "http://localhost:27221/api/Charging/FindByModel",

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 FindByModel(string strQuery)

{

TB_CHARGING oData = Newtonsoft.Json.JsonConvert.DeserializeObject(strQuery);

return "ChargingData" + oData.ID;

}

貌似又可行,没有任何问题啊。根据上面的推论,我们去掉[HttpGet]也是可行的,好,我们注释掉[HttpGet],运行起来试试。

如果这种情况下,再把[HttpGet]注释掉,数据就接收不到了。

最后结论:所有的WebApi方法最好是加上请求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]),不要偷懒,这样既能防止类似的错误,也有利于方法的维护,别人一看就知道这个方法是什么请求。

二、post请求

在WebApi的RESETful风格里面,API服务的增删改查,分别对应着http的post/delete/put/get请求。我们下面就来说说post请求参数的传递方式。

1、基础类型参数

(1)传递一个参数

post请求的基础类型的参数和get请求有点不一样,我们知道get请求的参数是通过url来传递的,而post请求则是通过http的请求体中传过来的,WebApi的post请求也需要从http的请求体里面去取参数。

$.ajax({

type: "post",

url: "http://localhost:27221/api/Charging/SaveData",

data: { "": "Jim" },

success: function (data, status) {}

});

[HttpPost]

public bool SaveData([FromBody]string NAME)

{

return true;

}

我们一般的通过url取参数的机制是键值对,即某一个key等于某一个value,而这里的FromBody和我们一般通过url取参数的机制则不同,它的机制是=value,没有key的概念,并且如果你写了key(比如你的ajax参数写的{NAME:"Jim"}),后台反而得到的NAME等于null。不信你可以试试。

(2)传递多个参数

传递多个参数,使用dynamic是一个很不错的选择。

$.ajax({

type: "post",

url: "http://localhost:27221/api/Charging/SaveData",

contentType: 'application/json',

data: JSON.stringify({ NAME: "Jim",DES:"备注" }),

success: function (data, status) {}

});

[HttpPost]

public object SaveData(dynamic obj)

{

var strName = Convert.ToString(obj.NAME);

return strName;

}

2、实体作为参数

(1)单个实体作为参数

上面我们通过dynamic类型解决了post请求基础类型数据的传递问题,那么当我们需要传递一个实体作为参数该怎么解决呢?

$.ajax({

type: "post",

url: "http://localhost:27221/api/Charging/SaveData",

data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },

success: function (data, status) {}

});

[HttpPost]

public bool SaveData(TB_CHARGING oData)

{

return true;

}

上面这种方法是可以的。指定指定contentType为application/json是不是也可以呢

var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };

$.ajax({

type: "post",

url: "http://localhost:27221/api/Charging/SaveData",

contentType: 'application/json',

data: JSON.stringify(postdata),

success: function (data, status) {}

});

[HttpPost]

public bool SaveData(TB_CHARGING lstCharging)

{

return true;

}

(2)实体和基础类型一起作为参数传递

var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };

$.ajax({

type: "post",

url: "http://localhost:27221/api/Charging/SaveData",

contentType: 'application/json',

data: JSON.stringify({ NAME:"Lilei", Charging:postdata }),

success: function (data, status) {}

});

[HttpPost]

public object SaveData(dynamic obj)

{

var strName = Convert.ToString(obj.NAME);

var oCharging = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(obj.Charging));

return strName;

}

3、数组作为参数

(1)基础类型数组

var arr = ["1", "2", "3", "4"];

$.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(string[] ids)

{

return true;

}

(2)实体集合

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、后台发送请求参数的传递

都是通过前端的ajax请求去做的,我们知道,如果调用方不是web项目,比如Android客户端,可能需要从后台发送http请求来调用我们的接口方法。

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);

}

三、put请求

WebApi里面put请求一般用于对象的更新。它和用法和post请求基本相同。同样支持[FromBody],同样可以使用dynamic。

1、基础类型参数

$.ajax({

type: "put",

url: "http://localhost:27221/api/Charging/Update",

contentType: 'application/json',

data: JSON.stringify({ ID: "1" }),

success: function (data, status) {}

});

[HttpPut]

public bool Update(dynamic obj )

{

return true;

}

2、实体作为参数

和post请求相同。

四、delete请求

参数传递机制和post也是基本相同。

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: "delete",

url: "http://localhost:27221/api/Charging/OptDelete",

contentType: 'application/json',

data: JSON.stringify(arr),

success: function (data, status) {}

});

[HttpDelete]

public bool OptDelete(List lstChargin)

{

return true;

}

五、总结

以上比较详细的总结了WebApi各种请求的各种参数传递

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值