0

So I'm trying to call my post method of web api(.net 4.0) as below.

public class ApiClientController : ApiController
{
  [HTTP Post]
  public string RequestMethod(ParamClass MyClass)
    {
      Dostuff\\
    }
}

Calling this from my windows service (.net 3.5) as below

WebClient client = new WebClient();
string webApiUrl = "http://localhost:51482/";
ParamClass param = new ParamClass() { //set params };

//using System.Runtime.Serialization 
Json.DataContractJsonSerializer serializer = new 
Json.DataContractJsonSerializer(param.GetType());

MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, param);

string serialisedData = Encoding.Default.GetString(ms.ToArray());
var response = 
client.UploadString("http://localhost:51482/api/ApiClient/RequestPapp", 
serialisedData);

Also my Param class of windows service looks like this

[DataContract]
public class ParamClass
{
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public string refNo { get; set; }
    [DataMember]

}

But in my web api ParamClass MyClass is null at post call and values are not comin(on debug). I have tried adding [DataContract] and [DataMember] in webapi Paramclass also but no luck. Earlier I was performing this task from windows service by

  client.PostAsJsonAsync<ParamClass>("/api/ApiClient/RequestPapp", param);

And it worked.But I have to use .net 3.5 and httpClient is 4.0 class.

Please help me out. Thanks in advance.

  • 1
    Try debugging. Use a sniffer like wireshark or fiddler and compare working and non working. Usually you have to add http headers to app. – jdweng Aug 10 '18 at 15:08
  • Try setting `client.Headers.Add(HttpRequestHeader.ContentType, "application/json");` as shown [here](https://stackoverflow.com/a/25673701). Possibly also you will need to do `client.Headers.Add(HttpRequestHeader.Accept, "application/json");` as shown in comments [here](https://stackoverflow.com/a/25673701). – dbc Aug 10 '18 at 19:36

0 Answers0