AngularJs& Web API - 无法使用$ http.post检索发布数据

时间:2014-11-25 03:19:16

标签: angularjs http post asp.net-web-api asp.net-ajax

这是我的网络API方法:

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<HttpResponseMessage> Register([FromBody] string data)
    {
      //data is always null 
    }

AngularJs方面:

        try {
            var postObj = new Object();
            postObj.UserName = $scope.RFId;
            ... Shortened for clarity...
            postObj.UserType = $scope.userType;

            //var validJson = JSON.stringify(postObj, "\t");
            //validJson = '"' + validJson + '"';
            postObj = '"' + postObj + '"';

            $http({
                method: 'POST',
                url: 'http://localhost:65337/api/Account/Register',
                data: postObj,
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(function (result) {
                console.log(result);
            }, function (error) {
                console.log(error);
            });

结果: WebApi无法识别任何数据或返回0 ....这就是fiddler捕获的帖子:

POST http://localhost:65337/api/Account/Register HTTP/1.1
Host: localhost:65337
Connection: keep-alive
Content-Length: 82
Accept: application/json, text/plain, */*
Origin: http://localhost:65337
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)           Chrome/39.0.2171.65 Safari/537.36
Content-Type: application/json
Referer: http://localhost:65337/WebApp/index.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

0=%22&1=%5B&2=o&3=b&4=j&5=e&6=c&7=t&8=+&9=O&10=b&11=j&12=e&13=c&14=t&15=%5D&16=%22 // <- Not sure what my post data is formatted like so...

非常感谢任何帮助或指示。感谢

1 个答案:

答案 0 :(得分:0)

您需要对数据进行编码,请查看有关如何使用Web API 2 with AngularJS的文章。