【问题标题】:Parameters are not getting passed from angular to Web API in the POST call在 POST 调用中,参数没有从 Angular 传递到 Web API
【发布时间】:2016-09-27 04:36:05
【问题描述】:

下面是我的角度和 Web APi 代码。在 post 方法中,null 被传递而不是印度 角度代码:

HWApp.controller('TestCtrl', function ($scope, $http) {
     $scope.SendData = function (Data)
      {
        $scope.whoo = Data;
        console.log(Data);

        $http({
         url: "api/call/firstCall",
         dataType: 'json',
         method: 'POST',
         data: "India",
          headers: {
          "Content-Type": "application/json"
          }
           }).success(function (response) {
            $scope.whoo = response;
            })
            .error(function (error) {
           alert(error);
            });
        }
      }
    );

Web API 控制器

  public class CallController : ApiController
    {
        [HttpGet]
        public string firstCallGet( )
        {
            return "Get";
        }


        [HttpPost]
        public string firstCall([FromBody] string a)
        {
            return a;
        }
    }

【问题讨论】:

  • 我也试过这个 data: { data: 'India' } 但同样的 null 被传递了。
  • 看看这是否有帮助:stackoverflow.com/questions/30957248/…
  • 到目前为止我所理解的复杂类型 [FromUri] 是必需的,但对于我们需要的简单类型 [FromBody] 我在这里使用简单的。在上面的文章中,他们使用的是复杂类型。

标签: angularjs asp.net-web-api angular-ui-router asp.net-web-api2 asp.net-web-api-routing


【解决方案1】:

您的数据参数应该是 JSON 对象。

data :{country : "India" }

定义一个模型类来自动反序列化。

Public class CountryViewModel{ Public string Country{get; set;} }

Web Api 控制器应该如下

public class CallController : ApiController { [HttpPost] public string FirstCall( CountryViewModel in) { return in.Country; } }

【讨论】:

  • CountryViewModel 中的属性不匹配,json 返回country,模型预期为Country
  • 但是,有什么方法可以在不反序列化的情况下做到这一点?
  • 通常前端开发人员抱怨在 JSON 中返回大写的键名。所以我们可以在应用程序启动中添加以下代码,上面的代码将按原样工作。 odetocode.com/blogs/scott/archive/2013/03/25/…
  • 使用From body stackoverflow.com/questions/13771032/…检查此选项
猜你喜欢
  • 1970-01-01
  • 2014-07-18
  • 2019-02-17
  • 2014-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多