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.

Http POST request with jQuery ajax

One of the most common scenarios is making client side Http calls to URLs to external or internal domain using jQuery ajax. In this demo, I’ll show how to call Page static method of an ASP.net method written for an aspx page using C#. The requirement is to use headers that need to be passed along with POST data.

var dataSent = "{firstName : '" + firstName + "', lastName: '" + lastName + "', pID: '" + pID + "'}";

I used the following Javascript method to generate Guid which is RFC4122 version 4 compliant solution.

var Guid = createGuid();

function createGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}

Below is the jQuery ajax POST request calling the Page static method DemoMethod in the DemoPage.aspx.cs file with the following signature:

Server-side public static method:

[WebMethod]

public static string DemoMethod(string firstName, string lastName, string pID) {return "demo";}

Client-side jquery ajax call:

$.ajax({
type: ‘POST’,
url: “DemoPage.aspx/DemoMethod”,

contentType: “application/json; charset=utf-8”,
dataType: ‘json’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
‘firstName’: firstName,
‘lastName’: lastName,
‘x-requestKey’: Guid
},
data: dataSent,
async: false,
success: function (response) {
alert(response);
if (response != null && response.d != null) {
alert(response.d);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(‘error’);
}
});

The response in the success part will be received by the object “response” and can be accessed using the response.d property.