【发布时间】:2015-02-04 16:28:43
【问题描述】:
我正在尝试将自定义对象和 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();
}
【问题讨论】:
-
消息正文是否应该包含格式为 JSON 的
CustomData?如果是这样,类型需要是Stream然后你反序列化它。 -
是的,我想我正在尝试将对象格式化为 JSON,您介意详细说明一下,类型需要流式传输吗?
-
你看过使用
PostAsJsonAsync<T>吗? -
当然,除非
CustomData对象有某种反序列化步骤,例如DataContract。 -
@RachaelM 抱歉,我的意思是链接
PostAsync<T>,这样您就可以直接发布对象,而无需先转换为 Json。
标签: c# web-services wcf rest dotnet-httpclient