Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用GET将复杂的JS对象从angular传递到c#WebApi_Javascript_C#_Angularjs_Http_Asp.net Web Api - Fatal编程技术网

Javascript 使用GET将复杂的JS对象从angular传递到c#WebApi

Javascript 使用GET将复杂的JS对象从angular传递到c#WebApi,javascript,c#,angularjs,http,asp.net-web-api,Javascript,C#,Angularjs,Http,Asp.net Web Api,我试图将复杂对象从angular传递到C#WebApi控制器。我写这段毫无意义的代码是为了学习 JS代码: angular.module('app').controller('ExampleController', function($scope, $http) { var self = this; var obj = { val1: { val2: { val3: true } } }; self.exampleGet

我试图将复杂对象从
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#代码:

公共类示例控制器:ApiController
{
[路线(“rest/myconso/examplepost”)]
[HttpPost]
公共IHttpActionResult示例Post(IDictionary查询)
{
返回Ok();
}
[路线(“rest/myconso/exampleget”)]
[HttpGet]
公共IHttpActionResult示例获取([FromUri]IDictionary查询)
{
返回Ok();
}
}
POST
方法可以像预期的那样完美地工作,但是
GET
方法不能。
查询
参数始终为空

我的代码有什么问题


谢谢

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);
    ...
}
可以映射到以下内容:

public IHttpActionResult ExampleGet(string foo, string baz)
{
    ...
}

这很有效,谢谢。我知道在使用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)
{
    ...
}