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

问题描述 投票:1回答:3

我创建了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形式。我能拥有吗?如果不是,我可以为提到的RequestMessage创建JSON字符串的另一种方式是什么?

c# json wcf operationcontext weboperationcontext
3个回答
1
投票

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


1
投票

我尝试了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;
}

0
投票

我实际上并没有完全理解这个问题,但作为我建议的建议;

您应该像这样为Json设计Web Config;

    <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上试用您的Web服务,您可以以JSON或您想要的方式请求和响应。

© www.soinside.com 2019 - 2024. All rights reserved.