JQuery Ajax POST/GET 请求至 ASP.NET WebAPI
1.注意要点:ajax提交请求的dataType参数、contentType参数值应该分别为
dataType: 'json' 和 contentType: 'application/json;charset=utf-8'
不然会报js跨域啊,Method 错误啊 等等一些乱七八糟的js错误.
下面直接上代码:
前端代码:
1 <!DOCTYPE html>
2
3 <html xmlns="http://www.w3.org/1999/xhtml">
4
5 <head runat="server">
6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7 <title></title>
8 <script src="js/jquery-2.2.3.min.js"></script>
9 <script type="text/javascript">
10 $(function () {
11 $('#getData').click(function () {
12 $.ajax({
13 url: 'http://localhost:58737/api/userInfo/getlist',
14 type: 'get',
15 dataType: 'json',
16 contentType: 'application/json;charset=utf-8',
17 success: function (data) {
18 //以表格的形式在浏览器控制台显示数据,IE下不支持
19 console.table(data);
20 }
21 });
22 });
23
24 $('#test').click(function () {
25 var school = {};
26 school.SchoolID = 1;
27 school.SchoolName = "学校1";
28 var students = [];
29 for (var i = 0; i < 3; i++) {
30 var student = {};
31 student.StudentID = (i + 1);
32 student.StudentName = "学生" + (i + 1);
33 student.SchoolID = 1;
34 students.push(student);
35 }
36 school.Students = students;
37 console.log(JSON.stringify(school));
38 $.ajax({
39 url: 'http://localhost:58737/api/Test/AddSchool',
40 type: 'post',
41 dataType: 'json',
42 contentType: 'application/json;charset=utf-8',
43 data: JSON.stringify(school),
44 success: function (data) {
45 console.table(data);
46 },
47 error: function () { },
48 beforeSend: function () { },
49 complete: function () { }
50 });
51 });
52 });
53 </script>
54 </head>
55
56 <body>
57 <form id="form1" runat="server">
58 <div>
59 <input type="button" value="跨域获取数据" id="getData" />
60 <br />
61 <hr />
62 <input type="button" value=" Test " id="test" />
63 </div>
64 </form>
65 </body>
66
67 </html>
后台控制器代码:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Net;
5 using System.Net.Http;
6 using System.Web.Http;
7
8 namespace WebApi_demo.Controllers
9 {
10 public class TestController : ApiController
11 {
12 /// <summary>
13 /// post /api/Test/AddSchool
14 /// </summary>
15 [HttpPost]
16 public SchoolModel AddSchool(SchoolModel item)
17 {
18 return item;
19 }
20 }
21 public class SchoolModel : School
22 {
23 public List<Student> Students { get; set; }
24 }
25 public class School
26 {
27 public int SchoolID { get; set; }
28 public string SchoolName { get; set; }
29 }
30 public class Student
31 {
32 public int StudentID { get; set; }
33 public string StudentName { get; set; }
34 public int SchoolID { get; set; }
35 }
36 }
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Net;
5 using System.Net.Http;
6 using System.Web.Http;
7
8 namespace WebApi_demo.Controllers
9 {
10 public class UserInfoController : ApiController
11 {
12 /// <summary>
13 /// 获取用户信息集合的方法
14 /// </summary>
15 /// <returns>返回用户信息集合</returns>
16 public IHttpActionResult GetList()
17 {
18 //对象集合模拟数据
19 List<UserInfo> list = new List<UserInfo>()
20 {
21 new UserInfo()
22 {
23 Id = 1,
24 UserName = "1张三",
25 UserPass = "FDASDFAS",
26 Email = "zhangsan@163.com",
27 RegTime = DateTime.Now
28 },
29 new UserInfo()
30 {
31 Id = 2,
32 UserName = "2李四",
33 UserPass = "FDASDFAS",
34 Email = "lisi@163.com",
35 RegTime = DateTime.Now
36 },
37 new UserInfo()
38 {
39 Id = 3,
40 UserName = "3王五",
41 UserPass = "FDASDFAS",
42 Email = "wangwu@163.com",
43 RegTime = DateTime.Now
44 },
45 new UserInfo()
46 {
47 Id = 4,
48 UserName = "4赵六",
49 UserPass = "FDASDFAS",
50 Email = "zhaoliu@163.com",
51 RegTime = DateTime.Now
52 },
53 new UserInfo()
54 {
55 Id = 5,
56 UserName = "5田七",
57 UserPass = "FDASDFAS",
58 Email = "tianqi@163.com",
59 RegTime = DateTime.Now
60 },
61 new UserInfo()
62 {
63 Id = 6,
64 UserName = "6王八",
65 UserPass = "FDASDFAS",
66 Email = "wangba@163.com",
67 RegTime = DateTime.Now
68 }
69 };
70 return Ok(list);
71 }
72
73 public class UserInfo
74 {
75 public int Id { get; set; }
76
77 public string UserName { get; set; }
78
79 public string UserPass { get; set; }
80
81 public string Email { get; set; }
82
83 public DateTime RegTime { get; set; }
84 }
85 }
86 }
效果图:

(二)Asp.Net WebApi+JQuery Ajax的Post请求整理
一、总结 1.WebApi 默认支持Post提交处理,返回的结果为json对象,前台不需要手动反序列化处理。 2.WebApi 接收Post提交参数需要指定([FromBody] string name) 3.WebApi 中如果只接收一个基础类型参数,不能指定key的名称 4.WebApi Post请求Action只能接收一个参数,也就是说一个Action中[FromBody]仅可指定一次 5.WebApi Post请求处理多个参数可以使用类对象方式接收参数例如:Student 6.在接收Post参数时,如果不想定义类,可以使用Newtonsoft.Json.Linq的JObject json对象容器接收参数 7.(不推荐使用)此接收参数可以使用dynamic本质是使用的JObject,但是提交参数需要指定字符串类型,contentType: ‘application/json’,类似WebServer中的指定方式 8.在WebApi的Post请求处理中,后台的Action名称不能使用“GetXXX”方式命名 二、验证代码 1.单个参数传递 Post获取请求参数需要指定参数来源 [FromBody], Post方式提交时,Action的名称不能使用’Get’名称开头, 如果只接收一个基础类型参数,不能指定key的名称 后台: 复制代码 /// /// Post获取请求参数需要指定参数来源 [FromBody] /// /// /// public string ShowName([FromBody] string name) { return $“您传入的名字:‘{name}’”; } public Dictionary<string, string> FindList([FromBody] bool IsShow) { Dictionary<string, string> dict = new Dictionary<string, string>(); if (IsShow) { dict.Add(“name1”, “张三”); dict.Add(“name2”, “李四”); } return dict; } 复制代码 JavaScript: 复制代码 $.post(’/api/postuser/showname’, { ‘’: ‘张三丰’ }, function (data) { console.info(data); alert(data); }); $.post(’/api/postuser/FindList’, { ‘’: true }, function (data) { console.info(data); alert(data); }); 复制代码 二、多个参数传递 1.指定类类型 Student 后台: public class Student { public string Name { get; set; } public int Age { get; set; } } 复制代码 /// /// Post获取参数可以接收对象类型,接收多个参数 /// /// /// public string ShowName2([FromBody] Student stu) { return $"’{stu.Name}'的年龄为:{stu.Age}"; } 复制代码 javascript: 复制代码 $.post(’/api/postuser/showname2’, { name: ‘张三丰’, age: 19 }, function (data) { console.info(data); alert(data); }); 复制代码 2.使用JObject 后台: 复制代码 /// /// 在接收Post参数时,如果不想定义类,可以使用Newtonsoft.Json.Linq的JObject json对象容器接收参数 /// /// /// public object ShowName3([FromBody] JObject obj) { return new { name = obj[“name”], age = obj[“age”], success = true }; } 复制代码 javascript: 复制代码 //如果使用JObject,使用对象提交或者使用字符串提交后台都能获取成功 $.post(’/api/postuser/showname3’, { name: ‘张三丰’, age: 19 }, function (data) { console.info(data); alert(data); }); 复制代码 3.使用dynamic(不推荐) 后台: 复制代码 /// /// 在接收Post参数时,如果前台传入参数为一个字符串,可以使用dynamic类型接收,不需要指定[FromBody] /// 此处obj的真正类型:FullName = “Newtonsoft.Json.Linq.JObject” /// /// /// public object ShowName3(dynamic obj) { return new { name = obj[“name”], age = obj[“age”], success = true }; } 复制代码 javascript: 复制代码 //需要指定参数类型:contentType: ‘application/json’,类似WebServer中的指定方式 $.ajax({ url: ‘/api/postuser/showname3’, type:‘post’, contentType: ‘application/json’, data: JSON.stringify({ name: ‘张三丰’, age: 19 }), success: function (data) { console.info(data); alert(data); } }); 复制代码 Asp.Net WebApi+AngularJs $http的Post请求整理 一、总结 1.后台使用如上相同 2.$http服务的post在单个参数提交后台接收失败 3.$http的post提交后台要么使用类类型接收,要么使用JObject接收(包含单个或多个参数) 二、代码示例 1.单个参数 复制代码 //单个参数提交,后台接收失败 $http.post(’/api/postuser/showname’, { ‘’: ‘张三’ }).then(function (result) { console.info(result); alert(result.data); }).catch(function (err) { console.info(err); alert(err.data.Message); }); //单个参数提交,后台使用JObject接收成功 $http.post(’/api/postuser/showlist’, { isshow: false }).then(function (result) { console.info(result); alert(result.data); }).catch(function (err) { console.info(err); alert(err.data.Message); }); 复制代码 2.多个参数 复制代码 //多个参数提交,Student类型接收参数 $http.post(’/api/postuser/showname2’, { name: ‘张三’, age: ‘15’ }).then(function (result) { //正确请求成功时处理 console.info(result); alert(result.data); }).catch(function (result) { //捕捉错误处理 console.info(result); alert(result.data.Message); }); //多个参数提交,JObject接收参数 //WebApi,相应结果为json对象,不需要手动发序列化处理 $http.post(’/api/postuser/showname3’, { name: ‘张三’, age: ‘15’ }).then(function (result) { //正确请求成功时处理 console.info(result); alert(result.data.name); }).catch(function (result) { //捕捉错误处理 console.info(result); alert(result.data.Message); }); 复制代码

浙公网安备 33010602011771号