Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send POST json from C# to asp.net web api

Tags:

json

c#

asp.net

How is it possible to make a POST request to ASP.Net web api from C#. I have used Newtonsoft dll files to create the json, but, I am not able to send it to the api.

My code is :

        Login login = new Login
        {
            userid = username.Text,
            pass = pass.Text
        };
        string json = JsonConvert.SerializeObject(login, Formatting.Indented);

How to send this json to web api, and get a response ?

Edit

string url = "myurl";


        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json; charset=utf-8";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {

            json = json.Replace("\r\n","");
            //json = json.Replace("\",", "\","   + "\"" +"\u002B");
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            pass.Text = result.ToString();
        }
like image 757
Roshan Avatar asked Jul 14 '14 06:07

Roshan


1 Answers

I made it work, by having a few edits. Instead of directly serializing the json object, I used a class, and assigned values to it, and serialized it using JavaScriptSerializer. Thanks for your help Shekhar.

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json; charset=utf-8";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string loginjson = new JavaScriptSerializer().Serialize(new
            {
                userid = username.Text,
                password = pass.Text
            });

            streamWriter.Write(loginjson);
            streamWriter.Flush();
            streamWriter.Close();

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                pass.Text = result.ToString();
            }
        }
like image 96
Roshan Avatar answered Sep 21 '22 13:09

Roshan