我正在尝试将自定义对象和2个字符串值传递给启用了REST和SOAP的WCF服务
以下是服务合同
[OperationContract]
[WebInvoke(UriTemplate = "/AddData/{Name}/{Id}", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped )]
bool AddData(CustomData itm,string Name, string Id);
然后我有示例代码尝试使用HTTP Client调用服务,我遇到的问题是字符串值传入但对象值为null
我不确定我是否定义了错误的服务或错误地调用了服务?
private async void button1_Click(object sender, EventArgs e)
{
try
{
var client = new HttpClient();
var uri = new Uri("http://localhost:52309/Service1.svc/rest/AddData/test/1");
CustomData data = new CustomData ();
data.description = "TEST";
data.fieldid = "test1";
data.fieldvalue = "BLA";
string postBody = JsonSerializer(data);
HttpContent contentPost = new StringContent(postBody , Encoding.UTF8, "application/json");
HttpResponseMessage wcfResponse = await client.PostAsync(uri, contentPost).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
client.Dispose();
string responJsonText = await wcfResponse.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
}
}
public string JsonSerializer(FormsData objectToSerialize)
{
if (objectToSerialize == null)
{
throw new ArgumentException("objectToSerialize must not be null");
}
MemoryStream ms = null;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
ms = new MemoryStream();
serializer.WriteObject(ms, objectToSerialize);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
return sr.ReadToEnd();
}
答案 0 :(得分:1)
我通过添加解决了这个问题
[DataContract(Namespace = "CustomData")]
和[DataMember(Name = "fieldvalue")]
到类定义中的每个变量,然后使用PostAsJsonAsync调用它并直接传递对象。感谢@DanielPark和@DavidG指出了正确的方向