2012-03-11 35 views
0

您好我有我的服務器上運行此代碼:PUT請求WCF REST服務使用jQuery AJAX

[OperationContract] 
    [WebInvoke(UriTemplate = "createinvoice", Method = "PUT")] 
    public Invoice CreateInvoice(Invoice instance) 
    { 
     // TODO: Add the new instance of SampleItem to the collection 
     try 
     { 

      string icode = instance.InvoiceCode; 


      return new Invoice() {InvoiceCode = icode }; 
     } 
     catch(Exception) 
     { 
      throw new NotImplementedException(); 
     } 

    } 

現在,這對我的客戶端:

var instance = {}; 
    instance.InvoiceCode = "INV0004"; 
    //instance.AmountPaid = 1000; 
    alert (JSON.stringify(instance)); 
    $.ajax({ 
     //cache:false, 
     url : 'http://localhost/Mobile/POS/createinvoice/', 
     data: JSON.stringify(instance), 
     type: 'PUT', 
     dataType: 'json', 
     contentType: "application/json; charset=utf-8", 
     processData: false, 
     async:false, 
     success: function(msg){ 
      alert(JSON.stringify(msg)); 
     }, 
     error: function(jqXHR, exception){ 
      alert("error "+ jqXHR.status); 
     } 
    }); 

現在根據我讀過PUT方法不會在URL本身附加數據。現在每次我運行它使用螢火蟲,我看到一個404沒有發現錯誤。我在這方面實際上是新的,所以我現在還沒有確切的線索。與此相比,get方法相當容易。你能幫我弄清楚有什麼不對嗎?謝謝。

更新

我看螢火上的XHR,這是響應的一部分(HTML)

<p xmlns="">Endpoint not found. Please see the <a rel="help-page" href="http://localhost/Mobile/POS/help">service help page</a> for constructing valid requests to the service.</p> 

如果我讀它正確,它說我有什麼不對的實際要求我在做什麼?而且這種格式是錯誤的?更新的

結束

+0

不是這裏的問題,但服務器不發送'json',你期望得到'dataType:'json'' – gdoron 2012-03-11 05:16:33

+0

抱歉忘了放置responseformat和requestformat。看到我已經添加了responseformat和requestformat,但仍然是相同的錯誤。 – jongbanaag 2012-03-11 05:26:18

回答

1

試試這個,ResponseFormat = WebMessageFormat.Json

[OperationContract] 
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate = "createinvoice", Method = "PUT")] 
public Invoice CreateInvoice(Invoice instance){ 
    *** 
} 

編輯

根據jQuery documentationput並非所有瀏覽器都支持。

類型

缺省: 'GET' 請求的類型,使( 「POST」 或 「GET」), 默認是 「GET」。注意:其他HTTP請求方法(如PUT和 DELETE)也可以在此處使用,但它們不受所有 瀏覽器的支持。

+0

我已經添加了。我只是忘了把它加在我的問題上。但仍然無效。客戶端觸發了這個問題? – jongbanaag 2012-03-11 05:33:18

+0

你的URL是否正確?你是否直接在瀏覽器上試用它?期待這樣的事情,'/ Mobile/POS/*****。svc/createinvoice /' – 2012-03-11 05:37:13

+0

http://www.west-wind.com/weblog/posts/2008/Apr/21/jQuery-AJAX-calls WCF-REST-Service – 2012-03-11 05:37:48