Request a Quote

In ASP.Net C#, Call webpage asynchronously with get and post method type and additional parameters in callback method

In ASP.Net C#, Call webpage asynchronously with get and post method type and additional parameters in callback method

In ASP.Net C#, Call webpage asynchronously with get and post method type and additional parameters in callback method

Asynchronous method call is a mechanism in which control execution returns directly to the next statement without waiting for the method operation execution. Every asynchronous call is associated with a dedicated thread. IIS has limited number of application thread pools (default 5000 per CPU). IIS can handle that number of concurrent request at a time. So if you have a situation where you expect large number of concurrent requests in a single application, asynchronous method call will be a good practice. Where synchronous call executes by occupying 5000 threads, asynchronous can perform the same task with only 50 available threads. Here you can read more on thread pools here

In C# data posting with get() method in asynchronous calls can be done by just passing parameters in URL where as in asynchronous post() method for passing the parameters you will need to write them in stream asynchronously. For that .Net is providing reach HttpWebRequest class methods.

Recently I had a situation where my application was expecting very heavy user traffic and I had a requirement to store them into my database as well as also need to pass the data to a third party webpage. So I needed to pass the data asynchronously to that third party webpage without waiting for the response from that webpage. Also if any asynchronous call fails during the execution due to any data mismatch, I need to log the error along with an “id” from my database for that user request. And to achieve that I needed to pass some extra data like “UserId”, which was not a part of asynchronous method parameters. Also I could not add the “id” in webpage parameter collection as it was not a part of the third party webpage definition.
So to accomplish this I have sent the parameter of type Object array into asynchronous method request with method type post. Following are the example of code for asynchronous get method, asynchronous post method and asynchronous post method with extra parameters.

Example for asynchronous GET method:

protected void Page_Load(object sender, EventArgs e)
{
//For testing I have used current application’s about.aspx itself
//Passes id, firstname and lastname as a quesrystring in URL
GetMethodCall(“http://localhost:2839/about.aspx?id=1&firstname=abc&lastname=xyz”);
}
private static void GetMethodCall(string URL)
{
//Create new HttpWebRequest object for the passed URL using create method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);//BeginGetResponse is used to call asynchronously URL
IAsyncResult result =
(IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
request.Method = “GET”;
try
{
//Read the response for any future needs.
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
//Log the error
string errormessage = ex.Message;
}
}

 

Example for POST method:

protected void Page_Load(object sender, EventArgs e)
{
// GetMethodCall(“http://localhost:2839/about.aspx?id=1&firstname=abc&lastname=xyz”);
//For post data testing I have used current application’s aboutpost.aspx
PostMethodCall(“http://localhost:2839/aboutpost.aspx”);
}
private static void PostMethodCall(string URL)
{
//Create new HttpWebRequest object for the passed URL using create method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);//Set method verb type to POST
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;// BeginGetRequestStream is used to set post data content in asynchronously call
IAsyncResult result =
(IAsyncResult)request.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), request);}
private static void GetRequestCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
Stream postStream = request.EndGetRequestStream(asynchronousResult);//Set data to be post
string postData = “id=1&firstname=abc&lastname=xyz”;// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (Exception ex)
{
//Log the error
string errormessage = ex.Message;
}
}

You need to use same GetResponseCallback method as previous example.

Example for GET & POST methods with additional user defined parameters:

protected void Page_Load(object sender, EventArgs e)
{
// GetMethodCall(“http://localhost:2839/about.aspx?id=1&firstname=abc&lastname=xyz”);
//For post data testing I have used current application’s aboutpost.aspx
PostMethodCall(“http://localhost:2839/aboutpost.aspx”, “L001020″, “U112″);
}
private static void PostMethodCall(string URL, string logID, string userid)
{
//Create new HttpWebRequest object for the passed URL using create method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);//Set method verb type to POST
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;// BeginGetRequestStream is used to set post data content in asynchronously call
//Use 2nd parameter for asyncresult as oject type and pass additional parameters comma separated
IAsyncResult result =
(IAsyncResult)request.BeginGetRequestStream(new AsyncCallback(GetRequestCallback), new object[] { request, userid, logID });}
private static void GetRequestCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
object[] param = (object[])asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)param[0];
//Read additional parametrs using object array
string userid = param[1].ToString();
string MyUniqueLogID = param[2].ToString();
try
{
Stream postStream = request.EndGetRequestStream(asynchronousResult);//Set data to be post
string postData = “id=1&firstname=abc&lastname=xyz”;// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();// Start the asynchronous operation to get the response
//Use 2nd parameter for asyncresult as oject type and pass additional parameters comma separated
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), new object[] { request, userid, MyUniqueLogID });
}
catch (Exception ex)
{
//My custom log with my unique logID and userid
string errormessage = userid + “-” + MyUniqueLogID + “:” + ex.Message;
}
}private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
object[] param = (object[])asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)param[0];
//Read additional parametrs using object array
string userid = param[1].ToString();
string MyUniqueLogID = param[2].ToString();
try
{
//Read the response for any future needs.
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
//My custom log with my unique logID and userid
string errormessage = userid + “-” + MyUniqueLogID + “:” + ex.Message;
}
}

Similarly you can pass additional parameters in GET method type by calling same GetResponseCallback callback.

request.BeginGetResponse(new AsyncCallback(GetResponseCallback), new object[] { request, userid, MyUniqueLogID });

Additional information:

  • You can retrieve GET method parameters as follows:

  • You can retrieve POST method parameters as follows:

You can retrieve return value from asynchronous web page call using following code:

private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
// Request state is asynchronous.
object[] param = (object[])asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)param[0];
//Read additional parametrs using object array
string userid = param[1].ToString();
string MyUniqueLogID = param[2].ToString();
try
{
//Read the response for any future needs.
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
//Get response stream for check return values by external webpage
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//Get response in string object
string myResult = responseString;
if (myResult == “success”)
{
string status = “I am done”;
}
else
{
string status = “I am done with some error”;
}

// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
catch (Exception ex)
{
//My custom log with my unique logID and userid
string errormessage = userid + “-” + MyUniqueLogID + “:” + ex.Message;
}
}

Required additional namespaces

System.Net.HttpWebRequest
System.Text; // for Encoding.UTF8

Supported .NET Frameworks

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

Posted By: Kruti V Parmar

One thought on “In ASP.Net C#, Call webpage asynchronously with get and post method type and additional parameters in callback method

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2015 Trimantra Software Solution LLP- Software Outsourcing Company India. All rights reserved.