我创建了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字符串的另一种方式是什么?
将[DataMember]添加到要转换为JSON的成员变量上。
我尝试了DataContract
和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; }
}
然后我将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;
}
我实际上并没有完全理解这个问题,但作为我建议的建议;
您应该像这样为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或您想要的方式请求和响应。