C#从OperationContext读取JSON形式的请求内容

Read request content in JSON form from OperationContext in C#

我创建了如下 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中returns的内容如下:

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

我想要 JSON 形式的请求正文。我可以要吗?如果不是,我可以为提到的 RequestMessage?

创建 JSON 字符串的另一种方法是什么

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

其实我并没有完全理解这个问题,但作为一个建议,我可能会提出建议;

您应该像这样为 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 或您想要的方式请求和响应。

我尝试了 DataContractDataMember,它对我有用。

下面是示例代码:

[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;
}