2014-02-11 128 views
0

我有一个WCF REST服务,它有两个简单的方法。发送JSON数据到WCF服务?

[OperationContract] 
    [WebInvoke(Method="GET", 
       ResponseFormat=WebMessageFormat.Json, 
       RequestFormat=WebMessageFormat.Json, 
       UriTemplate = "request/{controlType}")] 
string GetJSONConfig(string controlType); 

[OperationContract] 
(Method = "POST", 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json, 
     UriTemplate = "save/{jsonString}")] 
string SaveJSON(string jsonString); 

第一种方法是从javascript代码中调用。但我在哪里发送JSON数据到第二个并获得404错误。

有人遇到这种类型的问题。

$(document).ready(function() { 

     var circle = function() { 
      this.x = 100; 
      this.y = 100; 
      this.r = 10; 
     }; 
     var x = new circle(); 
     var arr = []; 
     arr.push(x); 
     var jsonData = JSON.stringify(arr); 

     $('#serviceCall').click(function() { 
      $.ajax(
      { 
       url: 'http://localhost:52506/JsonDataService.svc/save/', 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       data: JSON.stringify(arr), 
       processData: true, 
       success: function (data) { 
        document.getElementById("data").value = data; 
       }, 
       error: function (data) { 
        document.getElementById("data").value = data; 
       } 
      }); 
     }); 
    }); 

这是javascript代码库。

+1

您在第二种方法中缺少一些语法。 [WebInvoke准确。 – ZiNNED

回答

0

您尝试达到POST调用的方式不正确。

我想建议您创建DTO类,它实际上是您的JSON的投影。

如果我没有弄错,WCF将使用DataContractSerializer自动映射它。

样本:

[OperationContract] 
[WebInvoke(UriTemplate = "/PlaceOrder", 
    RequestFormat= WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json, Method = "POST")] 
    bool PlaceOrder(OrderContract order); 

如果你想生流,做这样的事情:

[OperationContract(Name = “MyMethod”)] 
     [WebInvoke(Method = “POST”, 
     UriTemplate = “blablahblah”)] 
     string Method(Stream data); 
0

它有点语法错误!这是正确的。

[OperationContract] 
[WebGet(ResponseFormat=WebMessageFormat.Json, 
     UriTemplate = "request/{controlType}")] 
string GetJSONConfig(string controlType); 

当您使用GET ,你并不需要指定请求格式的大部分时间。因为您可以从URL调用GET方法。

对于POST

[OperationContract] 
WebInvoke(Method = "POST", 
    ResponseFormat = WebMessageFormat.Json, 
    RequestFormat = WebMessageFormat.Json, 
    UriTemplate = "save/{jsonString}")] 
string SaveJSON(string jsonString); 

在这里,你不需要指定UriTemplate = "save/{jsonString}",而不是UriTemplate = "save"将做的工作。 .NET会自动将jsonString转换为JSON。你只需要从客户端发送JSON(在你的JS代码中)。我希望它能帮助你!

+0

可以请你分享从Javascript客户端调用SaveJSON()操作的代码吗? – Arijit