前端通过js调用webpi
Get请求
1.一个参数时,在Ajax里的 data: { “id”: 123 }这个写法;
2.两个参数时,在Ajax里的 data:{ “userName”: “Superman”, “id”: 123};
3.无参数时,在Ajax里的 data:"";
4.传递一个实体时,data: user,后台方法用一个相同的实体接收,并在参数类型前加一个特性 如 ([FromUri]Users user) ;
5.传递一个实体时也可以将这个实体序列化后在传递 data: { userString: JSON.stringify(user) };
Post、Put、Delete请求
1.一个参数时,在Ajax里的 data: { “”: 123 } 注意这里的key不要写值,后台要在参数类型前加上特性,如 ([FromBody]int id) ;
2.传递json数据,如 data:user ,后台是可以直接用实体接收到的;
3.传递json序列化后的格式,后台可以用实体接收,需要指定contentType,
如 contentType: ‘application/json’ 后台可以直接用实体接收;
4.传递实体和字符串如 data: { “User”: user, “Info”: “123” } 时,后台可用 JObject 类型接收
后台调用
Get
string url = “http://localhost:9008/api/users/GetUserByName?username=superman”;
直接拼装url地址;
HttpClient方法:
var handler = new HttpClientHandler();//{ AutomaticDecompression = DecompressionMethods.GZip };
using (var http = new HttpClient(handler))
{
var response = http.GetAsync(url).Result;//拿到异步结果
Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
return response.Content.ReadAsStringAsync().Result;
}
HttpWebRequest方法:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 30 * 1000;
//request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
//request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
string result = "";
using (var res = request.GetResponse() as HttpWebResponse)
{
if (res.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader