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();
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With