How to post data to specific URL using WebClient in C#?

CsharpServer Side ProgrammingProgramming

We can Get and Post data from a Web API using Web client. Web client provides common methods for sending and receiving data from Server

Web client is easy to use for consuming the Web API. You can also use httpClient instead of WebClient

The WebClient class uses the WebRequest class to provide access to resources.

WebClient instances can access data with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.


UploadString Sends a String to the resource and returns a String containing any response.


class Program{
   public static void Main(){
      User user = new User();
         using (WebClient webClient = new WebClient()){
            webClient.BaseAddress = "";
            var url = "/posts";
            webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            webClient.Headers[HttpRequestHeader.ContentType] ="application/json";
            string data = JsonConvert.SerializeObject(user);
            var response = webClient.UploadString(url, data);
            var result = JsonConvert.DeserializeObject<object>(response);
      catch (Exception ex){
         throw ex;
class User{
   public int id { get; set; } = 1;
   public string title { get; set; } = "First Data";
   public string body { get; set; } = "First Body";
   public int userId { get; set; } = 222;


   "id": 101,
   "title": "First Data",
   "body": "First Body",
   "userId": 222
Published on 25-Sep-2020 14:45:09