1

我创建了 WCF RESTful 服务,如下所示:

[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/Customer/{customerID}/profile")]
string PutCustomerProfileData(string customerID);

我正在使用Postman调试它并在 BODY 中传递JSON数据,如下所示:

{ "customerID":"RC0064211", "TermsAgreed":"true" }

public string PutCustomerProfileData(string customerID)
{
    Message requestMessage = OperationContext.Current.RequestContext.RequestMessage;
}

它在 RequestMessage 中返回的内容如下:

{<root type="object">
  <customerID type="string">RC0064211</customerID>
  <TermsAgreed type="string">true</TermsAgreed>
</root>}

我想要这个 JSON 格式的请求正文。我可以拥有吗?如果不是,我可以为提到的创建 JSON 字符串的另一种方法是什么RequestMessage

4

3 回答 3

2

我尝试了DataContractandDataMember它对我有用。

下面是示例代码:

[OperationContract]
    [WebInvoke(Method = "PUT",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/Customer/{customerID}/verification")]
    string PutCustomerVerificationData(string customerID, CustomerVerification customerVerification);
}

[DataContract]
public class CustomerVerification
{
    [DataMember]
    public string PasswordHash { get; set; }

    [DataMember]
    public string PasswordSalt { get; set; }
}

然后我将该 DataContract 转换为 JSON 字符串并进一步使用它,如下所示:

public string PutCustomerVerificationData(string customerID, CustomerVerification customerVerification)
{
      JavaScriptSerializer js = new JavaScriptSerializer();
      string requestBody = js.Serialize(customerVerification);
      string serviceResponse = bllCustomerDetails.PutCustomerVerificationData(customerID, requestBody).Replace("\"", "'");
      return serviceResponse;
}
于 2017-12-25T06:12:06.227 回答
1

在要转换为 JSON 的成员变量上添加[DataMember] 。

于 2017-12-21T09:53:32.513 回答
0

我实际上并没有完全理解这个问题,但我可能会提出建议;

您应该像这样为 Json 设计 WebConfig;

    <services>
  <service name="Your Service Name"

    <endpoint address="" behaviorConfiguration="webHttp" binding="webHttpBinding"
              bindingConfiguration="webHttpBindingWithJsonP" contract="YourProjectName">

    </endpoint>
  </service>
</services>
<bindings>
  <webHttpBinding>
    <binding name="webHttpBindingWithJsonP" />

             </binding>
  </webHttpBinding>
</bindings>


<behaviors>
  <endpointBehaviors>
    <behavior name="webHttp">
      <webHttp />
    </behavior>
  </endpointBehaviors>

你的数据成员应该像这样(只是例子);

   [DataContract]
public class Customer
{
   [DataMember]
    public int ID { get; set; }

    [DataMember]
    public int customerID { get; set; }

}

此外,您可以在Fiddler 4上尝试您的网络服务,您可以请求和响应 JSON 或您想要的内容。

于 2017-12-21T14:31:33.187 回答