Rohit Sharma
Rohit Sharma

Reputation: 189

API POST call from Console Application

How to do the REST API POST Call from the console Application ?

I want to pass the class from the Console application to the REST API. My below code is working if I have to do the GET call but not for the POST. It is hitting the API but in the Parameter it is not passing anything.

API

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values

    //public void Post([FromBody]string value)
    //{

    //}
    public void Post([FromBody]Student value)
    {

    }



}

Console Application

 static async Task CallWebAPIAsync()
    {

        var student = new Student() { Id = 1, Name = "Steve" };

        using (var client = new HttpClient())
        {
            //Send HTTP requests from here. 
            client.BaseAddress = new Uri("http://localhost:58847/");
              client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            HttpResponseMessage response = await client.PostAsJsonAsync("api/values", student);
            if (response.IsSuccessStatusCode)
            {

            }
            else
            {
                Console.WriteLine("Internal server Error");
            }
        }
    }

The Same is working if I call from fiddler.

User-Agent: Fiddler Content-Length: 31 Host: localhost:58847 Content-Type: application/json

Request Body: { "Id":"1", "Name":"Rohit" }

Upvotes: 1

Views: 13800

Answers (3)

Aram Yako
Aram Yako

Reputation: 61

To be honest I don't know. It seems like your StringContent did not sterilize it to UTF8 which your restful API is trying to do by default. However, your console application should also do that by default.

The issue seemed to be that the restful API could not bind the byte data and therefor not assign the data to your class Student in the restful API.

What you can try to do is add following code before you make your post to API:

var encoding = System.Text.Encoding.Default;

It will tell you what is your default encoding type. It could be that UTF8 is not the default encoding for some reason.

Upvotes: 0

ANJYR
ANJYR

Reputation: 2623

This is working for me.

    public async Task CallWebAPIAsync()
    {
        var student  = "{'Id':'1','Name':'Steve'}";
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:58847/");
        var response = await client.PostAsync("api/values", new StringContent(student, Encoding.UTF8, "application/json"));
        if (response != null)
        {
            Console.WriteLine(response.ToString());
        }
    }

Upvotes: 3

Aram Yako
Aram Yako

Reputation: 61

You are not serializing the student object. You can try to send a StringContent

StringContent sc = new StringContent(Student)

HttpResponseMessage response = await client.PostAsJsonAsync("api/values", sc);

if this doesn't work (a long time I used StringContent). Use NewtonSoft sterilizer

string output = JsonConvert.SerializeObject(product);
HttpResponseMessage response = await client.PostAsJsonAsync("api/values", output);

Upvotes: 0

Related Questions