我正在使用Angular $资源将模型发布到webapi端点,但Angular会在请求有效负载中发送数据,而不是JSON正文或表单参数。因此,模型总是最终为空。
我的API如下:
public class UserController : APIController {
[HttpPost]
public void Disconnect(Models.Users.User model) {
}
}
请求标头是:
POST /siteapi/User/Disconnect HTTP/1.1
Host: rouge2
Connection: keep-alive
Content-Length: 125
Accept: application/json, text/plain, */*
Origin: http://rouge2
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-Type: application/json;charset=UTF-8
Referer: http://rouge2/Users
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: .ASPXAUTH=115C6015BDD5C1A9D111B0A9FBF05294B73287328566F65CB1BCB457DF206EF0916D4615B5914EB443AA567E860742AC14EAA2951B9C327260C4F00649694260A1B3960771FB6675FEE8F3E68B0BB46436020ACAB33ECE0D3E70B50D6569E52B27F69161762C10C19A806A12D3254DF60EF4758DEDCA529A91CB36C74B7FA7F4; __RequestVerificationToken=Rp4Vu8R67ziDNc36DoOLZH7KmEfumig1zFDmYiFWHTsWyf2I037xJQydcmLtOfaJ3ccc8GEZXmHoa8LBRusxKFRYVoy27GuFEfNhKKYS_hUysjwCjmsxw5OCK3RKsiXIAh1Gbi0PxcdqBfzctSJn9g2
请求有效负载:
{"Id":3,"FirstName":"Test","LastName":"User","Username":"testuser","IsApproved":true,"IsOnlineNow":true,"IsChecked":true}
如果我在Fiddler中测试,在正文中发布相同的JSON字符串,则会按预期正确填充模型。
是否有内置的模型绑定器可以在这种情况下工作,或者在我可以使用的地方预先构建的东西?
或者有人可以指点我的工作方向吗?
答案 0 :(得分:37)
您可以使用$http module
。
以下是一个例子:
<!DOCTYPE html>
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div ng-controller="TestController">
<ul ng-model="person">
<li>FirstName: {{person.FirstName}}</li>
<li>LastName: {{person.LastName}}</li>
<li>UserName: {{person.Username}}</li>
<li>IsApproved: {{person.IsApproved}}</li>
<li>IsOnlineNow: {{person.IsOnlineNow}}</li>
<li>IsChecked: {{person.IsChecked}}</li>
</ul>
</div>
<script type="text/javascript" src="~/scripts/angular.min.js"></script>
<script type="text/javascript">
function TestController($scope, $http) {
var data = { "Id": 3, "FirstName": "Test", "LastName": "User", "Username": "testuser", "IsApproved": true, "IsOnlineNow": true, "IsChecked": true };
$http.post(
'/api/values',
JSON.stringify(data),
{
headers: {
'Content-Type': 'application/json'
}
}
).success(function (data) {
$scope.person = data;
});
}
</script>
</body>
</html>
假设有以下控制器:
public class ValuesController : ApiController
{
[HttpPost]
public User Post(User model)
{
return model;
}
}
答案 1 :(得分:0)
对我来说这很好用。 下面是服务器端代码
{ key: 'three' }
,请求客户端代码将是,
[HttpPost]
public void Disconnect([FromBody] Models.Users.User model) { ... }