Quan Nguyen
Quan Nguyen

Reputation: 582

Posting a complex object with ASP.NET WebAPI

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; }
}

Upvotes: 2

Views: 7806

Answers (1)

Marcus Höglund
Marcus Höglund

Reputation: 16856

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

Upvotes: 6

Related Questions