【问题标题】:AngularJs Post to WebApi is always nullAngularJs 发布到 WebApi 始终为空
【发布时间】:2015-11-13 17:00:19
【问题描述】:

角度代码:

 getAuthorizationStatus: function () {
                    var deferred = $q.defer();
                     $http({
                        method: "POST",
                        url: url,
                        data: {
                            username: $scope.username,
                            password: $scope.password
                        },
                        contentType: 'application/json',
                        headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    }
                    }).success(deferred.resolve)
                      .error(deferred.reject);
                    return deferred.promise;
                },

我的服务器端代码:

  [HttpPost]
        public int ValidateUser([FromBody]Credentials credentials)
        {
            try
            {
                string username = credentials.username;
                string password = credentials.password;
          //Do stuff
        }
        catch (Exception ex)
        {
            throw ex;
            return -1;
        }

        return -1; // not valid user
    }

我遇到的问题是我可以使用 Api 方法,但里面的数据始终为空。我尝试了几种这样的组合:

  data:  JSON.stringify({
                            "username" : "username",
                            "password":"mypassword"
                        }),

没有骰子。

我做错了什么?

【问题讨论】:

  • 你为什么使用帖子?看起来你想要得到。
  • 这真的是客户端的问题吗?任何服务器端 Web 框架都应该可以访问数据主体帖子。你的服务器建立在什么上面。
  • @jbrown 不,您不想使用获取用户名和密码的请求!

标签: angularjs asp.net-mvc asp.net-web-api2


【解决方案1】:

将您的数据包含在 $.param() 中

例子:

data: $.param({ username: $scope.username,password: $scope.password })

【讨论】:

  • 不是每个人都可以在他们的项目中使用或想要使用 jQuery。我相信您也可以使用请求转换器。 stackoverflow.com/a/1714899/1784301
  • 是的,如果您使用的是 jQuery,我的解决方案是完美的,而且它的实现非常简单。或者如果你不想使用 jquery,你可以参考 Sean Larkin 的链接。
  • @amanpurohit,您的方法将解决问题,但会添加额外的依赖项。但我相信你的回答会帮助很多人。
  • @w2olves,我提到如果项目依赖于 jquery,我的解决方案很合适。!
【解决方案2】:

我会尝试更改$http POST 的默认和适当行为,而是让服务器从正确的位置读取数据。取自MVC controller : get JSON object from HTTP body?

[HttpPost]
public ActionResult Index(int? id)
{
    Stream req = Request.InputStream;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();

    InputClass input = null;
    try
    {
        // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
        input = JsonConvert.DeserializeObject<InputClass>(json)
    }

    catch (Exception ex)
    {
        // Try and handle malformed POST body
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    //do stuff

}

事实证明,MVC 并没有真正将 POST 正文绑定到任何 特定的类。您也不能只获取 POST 正文作为参数 ActionResult (建议在另一个答案中)。很公平。你需要 自己从请求流中获取并处理它。

【讨论】:

    【解决方案3】:

    在操作输入参数旁边使用[FromBody] 足以从请求中获取数据。您的问题是您通过 headers 覆盖 Angular 代码中的 content-type

    contentType: 'application/json',
    headers: {
       'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
    }
    

    必须是 'application/json' 才能发送 json 数据。只需删除该标题,它应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多