I am trying to pass a custom object and 2 string values to a WCF service that has REST and SOAP enabled
below is the service contract
[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);
then I have sample code to try call the service using HTTP Client , the issue I have is that the string values get passed in but the object value is null
Im not sure if I have defined the service wrong or calling the service wrong ?
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();
}
CustomDataformeatted as JSON? If so, the type needs to beStreamthen you deserialise it that way.PostAsJsonAsync<T>?CustomDataobject has some sort of deserialisation step, such as aDataContract.PostAsync<T>which lets you post the object directly without having to first convert to Json.