2013-02-12 56 views
4

發出POST到Web API我有以下POST方法問題,同時從JQuery的

public HttpResponseMessage Post([FromBody]string package) 

我有一個使用HttpCLient沒有問題控制檯應用程序的web API。當我試圖通過jQuery撥打電話時,我在包變量上得到null

這是我現在的代碼:

$.ajax({ 
     url: 'http://localhost:8081/api/Package/', 
     type: 'POST', 
     data: JSON.stringify(message),  
    contentType: "application/json;charset=utf-8", 
     success: function (data) { 
      alert(data.length); 

     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      alert('Status: '+xhr.status+', Error Thrown: '+thrownError); 

     } 
    }); 

「消息」變量是含有兩個屬性的複雜模型。

我會做什麼錯?

我會感謝你的幫助......

+0

如果您在動作參數上得到空值,您應該*總是*檢查ModelState以查看反序列化過程中是否發生了任何錯誤。你看到什麼了嗎? – 2013-02-12 00:53:05

+0

'message'是否有一個名爲'package'的屬性? – Snixtor 2013-02-12 00:53:46

+0

@Snixtor - 不...它沒有一個屬性叫包 – 2013-02-12 13:42:28

回答

0

有可能與結合發送到服務器

嘗試發送數據

$.ajax({ 
     url: 'http://localhost:8081/api/Package/', 
     type: 'POST', 
     data: { package : JSON.stringify(message) }   
     datatype: 'json', 
     success: function (data) { 
      alert(data.length); 

     }, 
     error: function (xhr, ajaxOptions, thrownError) { 
      alert('Status: '+xhr.status+', Error Thrown: '+thrownError); 

     } 
    }); 

價值響應的問題我假設你的JSON.stringify(message)返回一個字符串值

更新

public HttpResponseMessage Post([ModelBinder]string package) 

允許這麼做是爲了我包到來自世界各地的,而不只是身體的結合。

+0

嗨...感謝您的回覆...我試過了,它沒有'工作。我認爲我錯過了JQuery調用中的某些東西......但我不知道它是什麼。 – 2013-02-12 13:19:04

+0

我更新了我的答案。但我不確定這是不是你想去的 – frictionlesspulley 2013-02-12 14:23:08

+0

Thansks你的建議......這將需要一些時間....我會讓你知道發生了什麼... – 2013-02-12 14:54:25

1

我能在這裏找到另一篇文章的解決方案:Calling Web Api POST always receives null value from jQuery

我不得不修改我的代碼方式如下:

讀取的行:數據:JSON.stringify(消息),改變爲:數據:JSON.stringify( '=' +消息),

我去API post方法和加入的下面一行代碼:

包= package.Replace( 「=」, 「」);

爲了移除在JQuery文章中添加的'='。