我尝试将复杂对象从angular
传递到C# WebApi
控制器。我写了这个无意义的代码,以便学习。
JS代码:
angular.module('app').controller('ExampleController', function($scope, $http) {
var self = this;
var obj = {
val1: {
val2: {
val3: true
}
}
};
self.exampleGet = function() {
$http.get('rest/myconso/exampleget', {
params: {
query: obj
}
}).then(function success(response) {
console.log('success');
}, function error(response) {
console.log('error');
});
};
self.examplePost = function() {
$http.post('rest/myconso/examplepost', obj).then(function success(response) {
console.log('success');
}, function error(response) {
console.log('error');
});
};
});
C#代码:
public class ExampleController : ApiController
{
[Route("rest/myconso/examplepost")]
[HttpPost]
public IHttpActionResult ExamplePost(IDictionary<string, IDictionary<string, IDictionary<string, bool>>> query)
{
return Ok();
}
[Route("rest/myconso/exampleget")]
[HttpGet]
public IHttpActionResult ExampleGet([FromUri]IDictionary<string, IDictionary<string, IDictionary<string, bool>>> query)
{
return Ok();
}
}
POST
方法完全按预期工作,但不是GET
方法。 query
参数始终为空。
我的代码出了什么问题?
由于
答案 0 :(得分:1)
Angular提出的GET请求是:
/rest/myconso/exampleget?query=%7B%22val1%22:%7B%22val2%22:%7B%22val3%22:true%7D%7D%7D
基本上将查询字符串参数发送给{"val1":{"val2":{"val3":true}}}
Web API中没有内置机制将此查询字符串参数绑定到您期望的字典对象。您必须手动处理它:
public IHttpActionResult ExampleGet(string query)
{
var result = JsonConvert.DeserializeObject<IDictionary<string, IDictionary<string, IDictionary<string, bool>>>>(query);
...
}
这就是说,通常应避免传递诸如GET参数之类的复杂和嵌套结构。你最好传递简单的参数:
$http.get('rest/myconso/exampleget?foo=bar&baz=bazinga')
.then(function success(response) {
console.log('success');
}, function error(response) {
console.log('error');
});
可以映射到以下内容:
public IHttpActionResult ExampleGet(string foo, string baz)
{
...
}