[英]Passing JavaScript object to C# WCF service as Dictionary<string, object>
[英]c# Passing an object to a REST enabled WCF Service
我正在嘗試將自定義對象和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();
}
我通過將[DataContract(Namespace = "CustomData")]
和[DataMember(Name = "fieldvalue")]
到類定義中的每個變量,然后使用PostAsJsonAsync對其進行調用並直接傳遞該對象來解決了該問題。 感謝@DanielPark和@DavidG為正確方向的指針
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.