我已经创建了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字符串的其他方式是什么?
答案 0 :(得分:1)
在要转换为JSON的成员变量上添加 [DataMember] 。
答案 1 :(得分:1)
我尝试使用DataMember
和[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; }
}
,这对我有用。
以下是示例代码:
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;
}
然后我将DataContract转换为JSON字符串并进一步使用它,如下所示:
$2
答案 2 :(得分: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或您想要的内容。