2014-11-25 75 views
0

這是我的web 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 ....這是什麼提琴手抓住我的職位:

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

將'data'指定爲json對象而不是來自json.stringfy的內容。 $ http將在內部串聯。不要使用引號。 – Chandermani 2014-11-25 03:49:37

+0

我曾嘗試將postObj分配給數據,沒有stringify或沒有運氣的字符串,但是postObj是一個正確的Json對象?如果沒有,有什麼建議嗎? – OverMars 2014-11-30 01:08:42

回答

0

您需要編碼您的數據,看看我的文章如何使用Web API 2 with AngularJS

+0

偉大的職位,QQ,我發送用戶名/ PW作爲我的數據,所以我不能通過URL編碼發送數據,有沒有辦法讓WebAPI從$ http.Post正文拉動數據? – OverMars 2014-11-30 01:19:59

+1

看到這篇文章,它應該幫助你找到你做錯了什麼http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api – 2014-12-01 02:53:24