I have added a rest API to a WCF service, unfortunately I don't really understand how to handle the POST calls correctly. For example, at WCF Service is this Save Fuction:
Interface VB.Net:
<OperationContract()>
<WebInvoke(Method:="POST", UriTemplate:="/saveNewAZEntry", BodyStyle:=WebMessageBodyStyle.Wrapped, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function SaveNewAZEntry(ByVal NewAZEntry As AZEntry) As AZEntry
Function VB.Net:
Public Function SaveNewAZEntry(ByVal NewAZEntry As AZEntry) As AZEntry Implements IPMProService.SaveNewAZEntry
If NewAZEntry.start.Date = NewAZEntry.finished.Date And DateDiff(DateInterval.Minute, NewAZEntry.start, NewAZEntry.finished) >= My.Settings.MinAZDauer Then .......
Now I try to call this function in my application via the API:
C#:
private static HttpClient _client = new HttpClient();
private static string ServiceUrl = "http://localhost:64917/PMProService.svc/api";
[HttpPost]
internal static void SaveAZEntry(AZEntry azEntry)
{
var uri = new Uri($"{ServiceUrl}/saveNewAZEntry");
try
{
var jsonString = JsonConvert.SerializeObject(azEntry);
HttpContent content = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage response = _client.PostAsync(uri, content).Result;
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw ex;
}
}
Now the function is called via the API but the object is not passed to the function and is still null. What am I doing wrong here?
CodePudding user response:
Let me know if this is something that helps you:
public void SendDataToWCF(AZEntry aZEntry)
{
var uri = new Uri("http://localhost:64917/PMProService.svc/api/saveNewAZEntry");
string strParam = string.Concat("param1=", aZEntry.param1, "¶m2=", aZEntry.param2);
byte[] data = Encoding.ASCII.GetBytes(strParam);
// Create request
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.Method = "POST";
webrequest.ContentType = "application/x-www-form-urlencoded";
webrequest.ContentLength = data.Length;
//Send/Write data to your Stream/server
using (Stream newStream = webrequest.GetRequestStream())
{
newStream.Write(data, 0, data.Length);
}
// get the response
using (WebResponse resp = webrequest.GetResponse())
{
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
var resultS = reader.ReadToEnd();
// Do something with your response
}
}
}