JQuery Ajax POST/GET 请求至 ASP.NET WebAPI
dataType: ‘json‘ 和 contentType: ‘application/json;charset=utf-8‘
不然会报js跨域啊,Method 错误啊 等等一些乱七八糟的js错误.
下面直接上代码:
前端代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="js/jquery-2.2.3.min.js"></script>
<script type="text/javascript">
$(function () {
$(‘#getData‘).click(function () {
$.ajax({
url: ‘http://localhost:58737/api/userInfo/getlist‘,
type: ‘get‘,
dataType: ‘json‘,
contentType: ‘application/json;charset=utf-8‘,
success: function (data) {
//以表格的形式在浏览器控制台显示数据,IE下不支持
console.table(data);
}
});
});
$(‘#test‘).click(function () {
var school = {};
school.SchoolID = 1;
school.SchoolName = "学校1";
var students = [];
for (var i = 0; i < 3; i++) {
var student = {};
student.StudentID = (i + 1);
student.StudentName = "学生" + (i + 1);
student.SchoolID = 1;
students.push(student);
}
school.Students = students;
console.log(JSON.stringify(school));
$.ajax({
url: ‘http://localhost:58737/api/Test/AddSchool‘,
type: ‘post‘,
dataType: ‘json‘,
contentType: ‘application/json;charset=utf-8‘,
data: JSON.stringify(school),
success: function (data) {
console.table(data);
},
error: function () { },
beforeSend: function () { },
complete: function () { }
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="跨域获取数据" id="getData" />
<br />
<hr />
<input type="button" value=" Test " id="test" />
</div>
</form>
</body>
</html>后台控制器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApi_demo.Controllers
{
public class TestController : ApiController
{
/// <summary>
/// post /api/Test/AddSchool
/// </summary>
[HttpPost]
public SchoolModel AddSchool(SchoolModel item)
{
return item;
}
}
public class SchoolModel : School
{
public List<Student> Students { get; set; }
}
public class School
{
public int SchoolID { get; set; }
public string SchoolName { get; set; }
}
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int SchoolID { get; set; }
}
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApi_demo.Controllers
{
public class UserInfoController : ApiController
{
/// <summary>
/// 获取用户信息集合的方法
/// </summary>
/// <returns>返回用户信息集合</returns>
public IHttpActionResult GetList()
{
//对象集合模拟数据
List<UserInfo> list = new List<UserInfo>()
{
new UserInfo()
{
Id = 1,
UserName = "1张三",
UserPass = "FDASDFAS",
Email = "",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 2,
UserName = "2李四",
UserPass = "FDASDFAS",
Email = "",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 3,
UserName = "3王五",
UserPass = "FDASDFAS",
Email = "",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 4,
UserName = "4赵六",
UserPass = "FDASDFAS",
Email = "",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 5,
UserName = "5田七",
UserPass = "FDASDFAS",
Email = "",
RegTime = DateTime.Now
},
new UserInfo()
{
Id = 6,
UserName = "6王八",
UserPass = "FDASDFAS",
Email = "",
RegTime = DateTime.Now
}
};
return Ok(list);
}
public class UserInfo
{
public int Id { get; set; }
public string UserName { get; set; }
public string UserPass { get; set; }
public string Email { get; set; }
public DateTime RegTime { get; set; }
}
}
}效果图:

(二)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);
});
复制代码