2

How can I use WebClient object to send a POST request like this:

public static void SaveOrUpdateEntity(string url, object data)
{
    using (var client = new WebClient())
    {
        // TODO
    }
}

where its data is a Person object.

This is controller method

[HttpPost]
public void Post([FromBody]Person person)
{
    VeranaWebService.SaveOrUpdatePerson(person);
}

and Person class

public class Person
{
    public string Name { get; set; }
    public string FirstName { get; set; }
    public DateTime? BirthDate { get; set; }
    public byte[] Photo { get; set; }
}
2
  • 1
    One way is to serialize it using newtonsoft json serialization routines. Then on the API side, if the input is of type Person the binding engine reserializes it. Commented Jun 7, 2016 at 10:27
  • 1
    I would use HttpClient .. I personally find it easier to use. And yes, serialize your object using NewtonSoft.Json. Commented Jun 7, 2016 at 10:33

1 Answer 1

6

You can use Newtonsoft.Json which will help you serialize your data to a json object. It can be used like this

using Newtonsoft.Json;

public static void SaveOrUpdateEntity(string url, object data)
{    
    var dataString = JsonConvert.SerializeObject(data);

    using (var client = new WebClient())
    {
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
        response = client.UploadString(new Uri(url), "POST", dataString);
    }
}

To learn more about the newtonsoft library, read here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.