Click here to Skip to main content
15,883,901 members
Articles / Programming Languages / Javascript
Article

Using HttpModule to Handle Ajax Calls

Rate me:
Please Sign up or sign in to vote.
3.17/5 (4 votes)
26 Sep 2008BSD1 min read 30.9K   193   21  
Using HttpModule to handle Ajax calls in C#

Introduction

This is an article about how we can use httpmodule to handle an Ajax request.

I have added a new function to directly load the HTML container and HTML attributes so that we can attach with HTML elements. I added cross domain Ajax calls fucntionality.

  • onAjaxClick
  • onAjaxClickContainer
  • onAjaxClickCrossDomain
  • xmlHttpRequestObject1.createAjax();
  • xmlHttpRequestObject1.createAjaxContainer();
  • xmlHttpRequestObject1.createAjaxCrossDomain();

Background

This is the first sample that I have created using HttpModule. So I thought of using HttpModule with a bit of reflection and AJAX and creating a very basic AJAX Framework.

Now I am using ajaxScript in a resource file to access JavaScript in the handler.

The Code

Create an HttpModule class:

C#
namespace SomeDummyHttpModuleExample
{
    public class getAssemblyInformation
    {
        public void setAssemblyInformation(HttpApplication context,
            System.Reflection.Assembly a)
        {
            context.Session["set_assmbly_information"] = a.FullName;
        }
    }

    public class HttpModuleExample : IHttpModule
    {

        public String ModuleName
        {
            get { return "HttpModuleExample"; }
        }


        public void Dispose()
        { }

        public void Init(HttpApplication context)
        {
            //context.PreRequestHandlerExecute += new EventHandler(context_BeginRequest);
            //context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_BeginRequest);
        }


        void context_BeginRequest(object sender, EventArgs e)
        {
            //if (((HttpApplication)sender).Request.Url.ToString().IndexOf(
            //"smidxop=") == -1)

            string s123 = ((HttpApplication)sender).Response.ContentType;
            //((HttpApplication)sender).
            if (((HttpApplication)sender).Request.Url.ToString().IndexOf(
                "SomeDummyHttpModuleExample") == -1)
            {
                string scriptFromRes =
                    SomeDummyHttpModuleExample.Properties.Resources.ajaxScript.ToString();
                ((HttpApplication)sender).Context.Response.Write(scriptFromRes);
            }
            else
            {
                try
                {
                    string s = ((HttpApplication)sender).Request.Url.ToString();
                    string[] values = s.Split('?');
                    if (values.Length > 2)
                    {
						if (values[2].ToString() == 
                                                           "_c_d_caLL_f_cLiEnT")
                        {
                            System.Net.HttpWebRequest webReq = (
                                System.Net.HttpWebRequest)System.Net.WebRequest.Create(
                                values[1].ToString());
                            webReq.KeepAlive = false;

                            System.Net.HttpWebResponse webresponse;
                            webresponse = (System.Net.HttpWebResponse)webReq.GetResponse();

                            Encoding enc = System.Text.Encoding.GetEncoding(1252);
                            System.IO.StreamReader loResponseStream = new
                              System.IO.StreamReader(webresponse.GetResponseStream(), enc);

                            string Response = loResponseStream.ReadToEnd();

                            try
                            {
                                ((HttpApplication)sender).Response.Write(
                                    HttpUtility.HtmlDecode(Response));
                                ((HttpApplication)sender).Response.Flush();
                                ((HttpApplication)sender).Response.Close(); //End();
                            }
                            catch (Exception ex)
                            { }
                            

                        }
                        else
                        {
                            //'SomeDummyHttpModuleExample?' + namespace + '?' +
                            //method + '?' + parameters
                            AppDomain appDom = AppDomain.CurrentDomain;
                            foreach (Assembly aaa in appDom.GetAssemblies())
                            {
                                if (aaa.GlobalAssemblyCache == true)
                                    continue;
                                foreach (Type tys in aaa.GetTypes())
                                {
                                    if (tys.FullName.ToLower().Contains(
                                        values[1].ToLower().ToString()) &&
                                        tys.IsSubclassOf(typeof(BasePage)) == true)
                                    {
                                        foreach (MethodInfo mmm in tys.GetMethods())
                                        {
                                            if (mmm.Name == values[2].ToString())
                                            {
                                                string[] parameters;
                                                parameters = new string[] { };
                                                if (values[3].Trim().Length != 0)
                                                    parameters =
                                                        values[3].Trim().Split(',');

                                                object returnValue;
                                                object[] paramArray = new object[] { };
                                                if (parameters.Length == 0)
                                                    returnValue = mmm.Invoke(null, null);
                                                else
                                                {
                                                    paramArray =
                                                        new object[parameters.Length];
                                                    int g = 0;
                                                    foreach (string ss in parameters)
                                                    {
                                                        paramArray[g] = (object)ss;
                                                        g++;
                                                    }
                                                    returnValue = mmm.Invoke(null,
                                                        paramArray);
                                                }
                                                try
                                                {
                                                    ((
                                                    HttpApplication)sender).Response.Write(
                                                        Convert.ToString(returnValue));
                                                    ((HttpApplication)sender).Response.Flush();
                                                    //End();
                                                    ((HttpApplication)sender).Response.Close();
                                                }
                                                catch (Exception ex)
                                                { }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }                 
                }
                catch (Exception ex)
                {
                    ((HttpApplication)sender).Context.Response.Write(
                       ex.Message + " -- " + ex.StackTrace);
                    ((HttpApplication)sender).Context.Response.Flush();
                    ((HttpApplication)sender).Context.Response.Close();
                }
            }
        }
    }
}

Create a base class for Web pages:

C#
using System.Web;
using System.Web.UI;

namespace SomeDummyHttpModuleExample
{
    public class BasePage : Page
    {
        public BasePage(Type t) { }
        public BasePage() { }
    }
}

You can get rid of the base class if you want, just remove the check for the base class in the httpmodule class.

Add a reference of this DLL into your ASP.NET project. Use the following syntax to create an Ajax request.

C#
var xmlHttpRequestObject1 = 
	new xmlHttpRequestObject('callbackpage','dummyMethod','','handlecal');
//dummyMethod method should be a static method declared in the callbackpage class.

var xmlHttpRequestObject1 = 
    //or can directly pass the function reference handlecal
	new xmlHttpRequestObject('callbackpage','dummyMethod','',handlecal);

dummyMethod can be a parameterised or parameterless method. If it is parameterised, then we have to pass the parameter in a comma separated string. e.g.

C#
var xmlHttpRequestObject1 = new xmlHttpRequestObject
	('callbackpage','dummyMethod','one parameter only','handlecal');

var xmlHttpRequestObject1 = new xmlHttpRequestObject
   ('callbackpage','dummyMethod','one parameter only, second parameter','handlecal');

xmlHttpRequestObject(Class Complete Path,Static Method Name,
	Comma Separated Parameter List,Call back javascript function); 


xmlHttpRequestObject1.createAjax(); //To initiate request

function handlecal(resp) //call back handler with response ‘resp’
 {
     alert(resp);
 }
 
xmlHttpRequestObject1.createAjaxContainer(); //To initiate request to populate container

You can also pass the function reference as

C#
var xmlHttpRequestObject1 = new xmlHttpRequestObject
	('callbackpage','dummyMethod','one parameter only',handlecal); //Without quotes

Initiating an Ajax request to populate a container

C#
var xmlHttpRequestObject1 = new xmlHttpRequestObject('_Default','getServerTime',
    '','time');//time is Id of HTML container
xmlHttpRequestObject1.createAjaxContainer(); //createAjaxContainer function to
                                             //populate html element

Adding an HTML attribute to an HTML element to intiate an Ajax request on onclick function

C#
onAjaxClick="_Default,getFirstNameLastName,Lokesh$Lal,handlecal2" 
//Parameters seperated by $(dollar sign) in attribute.
//handlecal2 is name of function in javascript that will recieve response.
C#
onAjaxClickContainer="_Default,getFirstNameLastName,Lokesh$Lal,time"
//Parameters seperated by $(dollar sign) in attribute.
//time is Id of HTML container that will get populated with the response.

Configure Web.config to use this HttpModule:

XML
<system.web>
	<httpModules>
		<add name="SomeDummyHttpModuleExample" 
			type="SomeDummyHttpModuleExample.HttpModuleExample"/>

	</httpModules>

</system.web>

To read assembly information, I use appdomain to get the list of all loaded assemblies and then search for the specific type and calling its static method with parameters or without parameters.

You can use...

C#
if (aaa.GlobalAssemblyCache == true)
    continue;

... to avoid checking the type of all assemblies in module.

History

Added following functions:

  • onAjaxClick
  • onAjaxClickContainer
  • onAjaxClickCrossDomian
  • xmlHttpRequestObject1.createAjaxContainer();
  • 23rd September, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer
India India
Working on .NET technologies(windows, web, database, reporting, intergration services etc).

Comments and Discussions

 
-- There are no messages in this forum --