如何使用WCF在UriTemplate中传递JSON字符串而不使用查询字符串

时间:2017-07-19 07:13:39

标签: wcf c#-4.0 wcf-rest

http://localhost:51238/RestService.svc/FOSLoadingS1Opening?Data=[
{ 
"Name":"Sachin", 
"City":"Bengalueu", 
"FimStatus":"false", 
"Deno1":"50", 
"Deno2":"100", 
"Deno3":"500", 
"Deno4":"2000", 
"IndtVal1":"2500", 
"IndtVal2":"5000"  }]

我能够使用查询字符串传递json字符串。但是,当我想要传递没有查询字符串的传递时,我收到了错误。

http://localhost:51238/RestService.svc/FOSLoadingS1Opening/[
{ 
"Name":"Sachin", 
"City":"Bengalueu", 
"FimStatus":"false", 
"Deno1":"50", 
"Deno2":"100", 
"Deno3":"500", 
"Deno4":"2000", 
"IndtVal1":"2500", 
"IndtVal2":"5000"  }]

当我通过上述网址时,我收到错误"错误请求"。

我想在不使用查询字符串的情况下传递json字符串。请建议如何实现。

1 个答案:

答案 0 :(得分:0)

您必须使用WebInvoke方法POST。

[OperationContract]
[WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "SaveData/{id}")]
string SaveData(YourType typeObj);

现在从客户端构造对象并通过ajax调用发送json字符串化数据。

    var obj = {
        "Name":"Sachin", 
        "City":"Bengalueu", 
        "FimStatus":"false", 
        ...
    };
    $.ajax({
        type: "POST",
        url: "http://localhost/wcf.svc/SaveData/0",
        data: JSON.stringify(obj),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        processData: true,
        success: function (data, status, jqXHR) {
            alert("success..." + data);
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });