Site icon Tutexchange

How to POST DATA to ASP.NET CORE WEB API Using HttpClient from .Net Core Console Application

Advertisements

In this article, we will learn how to POST Data to ASP.NET Core WEB API Using HttpClient from .Net Core Console Application in simple steps.

In the previous two articles, we have learned how to consume data now in simple steps.

  1. How to Consume WEB API GET Method in .Net Core Console Application
  2. How to Consume WEB API GET Method with a parameter named id in .Net Core Console Application

Let’s Get Started

We already have a POST API developed in ASP.Net Core we are going to consume this API in the .Net Core Console Application.

POST API which we are going to call

Let’s first call POST API using Postman

URI: – https://localhost:44373/api/Music

We have URI we are going to use this below Json object which we are going to use as a request body.

{
  "Name": "Srivalli",
  "Length": "5.50",
  "Yearreleased": 2022,
  "Writer": "Chandrabose",
  "Singer": "Sid Sriram",
  "Genre": "Singing",
  "Rating": 5
}

We have set the setting header Content-Type: – application/json in POSTMAN to send the request.

In response, we are going to get the same json object along with songid.  

Creating Console Application

For Consuming APIs, we have created a .Net Core Application which Target Framework .Net 6.0 with the name Consoleconsumer.

Steps to POST data to Web API

  1. HttpClient class instance for sending HTTP Requests.
  2. Setting Base Address “https://localhost:44373
  3. Setting Accept Header “application/json”
  4. Adding a class with the name SongsModel which has properties and fields of response json. SongsModel class will be used for POST object along with it we are also going to use it while deserializing response.
  5. Next, we are calling PostAsync Method and Passing Request Uri (“/api/Music”) and also HttpContent as a parameter to it which will send a POST request to the specified Uri in an asynchronous way.
  6. DeserializeObject (response we are going to receive will be Json format which we need to map to .Net Type)

Method for POSTING API

In this method we are going to first create an instance of HTTPclient after that we are going to set Base Address “https://localhost:44373“.

Now if you see Music POST API we need POST data for that we need to add a class with similar properties and fields of API which takes input.

  public class SongsModel
  {
     public int SongId { get; set; }
     public string Name { get; set; }
     public string Length { get; set; }
     public int Yearreleased { get; set; }
     public string Writer { get; set; }
     public string Singer { get; set; }
     public string Genre { get; set; }
     public int Rating { get; set; }
 }

After adding the class next we are going to create an instance of a class and set some hardcode data to it for the demo you can automate it as per your request.

Next after assigning data to the class, we are going to create an instance of “StringContent” and pass content, encoding type and content type.

HttpContent body = new StringContent(JsonConvert.SerializeObject(songsModel), Encoding.UTF8, "application/json");

StringContent instance, we are going to pass it to PostAsync() method as an input parameter and also, we are going to set request Request-URI as “/api/Music“.

var response = client.PostAsync("/api/Music", body).Result;

As the PostAsync method gets called we are going to receive a response and, in this response, the first thing we are going to do is check the Status of it if it is a success then we are going to read the response and then Deserialize it.

The response which we are going to get is the same which we have sent one different parameter we are going to get is the Key (Primary key) to indicate data is saved in the database successfully.

Code Snippet

 static async Task PostJsonData()
        {
            using var client = new HttpClient();
            client.BaseAddress = new Uri("https://localhost:44373");

            var songsModel = new SongsModel()
            {
                SongId = 0,
                Name = "Srivalli",
                Rating = 5,
                Length = "5.50",
                Genre = $"Singing",
                Singer = $"Sid Sriram",
                Writer = $"Chandrabose",
                Yearreleased = DateTime.Now.Year
            };

            HttpContent body = new StringContent(JsonConvert.SerializeObject(songsModel), Encoding.UTF8, "application/json");
            var response = client.PostAsync("/api/Music", body).Result;

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(content))
                {
                    var objDeserializeObject = JsonConvert.DeserializeObject<SongsModel>(content);

                    Console.WriteLine("Data Saved Successfully.");

                    if (objDeserializeObject != null)
                    {
                        Console.WriteLine(objDeserializeObject.Name);
                    }
                }
            }

        }

Calling PostJsonData Method in Main() Method

 static void Main(string[] args)
 {
     PostJsonData().Wait();
 }

View of runtime receiving a response

Below snapshot after the deserialized Json object

In this article, we have learned how to POST Data to ASP.NET Core WEB API Using HttpClient from .Net Core Console Application in simple steps.

Welcome my New Dotnet Shorts #DOTNETSHORTS Series Hope you like it small and simple and focused.

Exit mobile version