如何将JSON参数传递给RESTful WCF服务?

时间:2015-03-30 10:08:52

标签: c# json wcf rest

我开发了Restful WCF服务,我需要传递一个json字符串作为输入。 json字符串是可变的。 这是我的服务:

[WebGet(UriTemplate = "{id}", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml)]
public string GetById(string id)
{

    string sampleItem = id;


    return sampleItem;
}

这是一个json的例子:

{  
   "name":"obj1",
   "x":11,
   "y":20,
   "obj":{  
      "testKey":"val"
   },
   "z":30,
   "tab":[  
      1,
      2,
      46
   ],
   "employees":[  
      {  
         "firstName":"John",
         "lastName":"Doe"
      },
      {  
         "firstName":"Anna",
         "lastName":"Smith"
      },
      {  
         "firstName":"Peter",
         "lastName":"Jones"
      }
   ]
}

http://localhost:7626/Service1/myjsonstring

我收到此错误:Erreur HTTP 400 - 错误请求。

P.S:如果我传递一个简单的字符串就行了。 任何想法PLZ

1 个答案:

答案 0 :(得分:1)

首先,我建议您为此目的使用POST方法。读取原始字符串的最简单方法是将其作为Stream。所以你的服务界面可能是这样的:

[ServiceContract]
public interface IService1
{
    [WebInvoke(Method = "POST", UriTemplate = "PostJson")]
    string PostJson(Stream request);
}

并实施:

public class Service1 : IService1
{
    public string PostJson(Stream request)
    {
        using (var reader = new StreamReader(request))
        {
            return "You posted: " + reader.ReadToEnd();
        }
    }
}

请同时检查您的Web配置是否正确:

<system.serviceModel>
  <services>
    <service name="WcfService1.Service1">
      <endpoint address="" behaviorConfiguration="restfulBehavior" 
                binding="webHttpBinding" bindingConfiguration=""
                contract="WcfService1.IService1">
      </endpoint>
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
        <serviceMetadata httpGetEnabled="true"/>
        <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>