ASP.Net Server side Http Web Request with Custom Headers

This post shows how to make HttpWebRequest from Asp.Net page using c#. Here, the requirement is to call an external API with Custom headers and sending json data in the page_load method. Reading the Html response from the stream and write it on the Aspx page. Gluid is the Global Unique Identifier generated in c#.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?pID=" + pID);

NameValueCollection nameValueCollection = new NameValueCollection
{
{ "firstName", firstName },
{ "lastName", lastName },
{ "x-requestKey", Gluid },
};
request.Headers.Add(nameValueCollection);
request.Accept = "application/json";
request.ContentType = "application/json";
request.Method = "POST";
request.AllowAutoRedirect = true;
byte[] bytes = Encoding.ASCII.GetBytes(dataSent);

request.ContentLength = bytes.Length;
Stream os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();

Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string html = streamReader.ReadToEnd();
Response.Write(html);

dataSent is the is json data read from a json file and sent as bytes.

For generating Gluid, use the following C# code:

public string GetUniqueIdentifier()
{
var guid = Guid.NewGuid().ToString();
return guid;
}

For similar Http POST request using jquery ajax, check out this post.

One thought on “ASP.Net Server side Http Web Request with Custom Headers

Leave a Reply to 918kiss report Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.