Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Web API Sending Body Data in HTTP Post REST Client

I need to send this HTTP Post Request:

 POST https://webapi.com/baseurl/login
 Content-Type: application/json

 {"Password":"password",
 "AppVersion":"1",
 "AppComments":"",
 "UserName":"username",
 "AppKey":"dakey" 
  }

It works great in RestClient and PostMan just like above.

I need to have this pro-grammatically and am not sure if to use

WebClient, HTTPRequest or WebRequest to accomplish this.

The problem is how to format the Body Content and send it above with the request.

Here is where I am with example code for WebClient...

  private static void Main(string[] args)
    {
        RunPostAsync();
    } 

    static HttpClient client = new HttpClient();

    private static void RunPostAsync(){

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            Inputs inputs = new Inputs();

            inputs.Password = "pw";
            inputs.AppVersion = "apv";
            inputs.AppComments = "apc";
            inputs.UserName = "user";
            inputs.AppKey = "apk";


            var res = client.PostAsync("https://baseuriplus", new StringContent(JsonConvert.SerializeObject(inputs)));

            try
            {
                res.Result.EnsureSuccessStatusCode();

                Console.WriteLine("Response " + res.Result.Content.ReadAsStringAsync().Result + Environment.NewLine);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Error " + res + " Error " + 
                ex.ToString());
            }

        Console.WriteLine("Response: {0}", result);
    }       

    public class Inputs
    {
        public string Password;
        public string AppVersion;
        public string AppComments;
        public string UserName;
        public string AppKey;
    }

This DOES NOW WORK and responses with a (200) OK Server and Response

like image 344
CraigJSte Avatar asked May 22 '18 01:05

CraigJSte


1 Answers

You are not properly serializing your values to JSON before sending. Instead of trying to build the string yourself, you should use a library like JSON.Net.

You could get the correct string doing something like this:

var message = JsonConvert.SerializeObject(new {Password = pw, AppVersion = apv, AppComments = acm, UserName = user, AppKey = apk});
Console.WriteLine(message); //Output: {"Password":"password","AppVersion":"10","AppComments":"","UserName":"username","AppKey":"dakey"}
like image 199
Jonathon Chase Avatar answered Sep 28 '22 06:09

Jonathon Chase