Create your own ASP.NET MVC Framework from scratch in 15 mins

Currently ASP.NET MVC is a big BLACK BOX. I have just tried to open this box.I have tried to create a very ver basic application in plain Dot Net which will try to implement a basic ASP.NET MVC fundamental.

Its not practical to use it...but you will actually come to know how things works in the box.

Heres what will happen roughly....



 
Request comes from browser
                  ||
                  V
HttpHandler will receive the request 
(The http handler is the main engine which will read the request and then call appropriate ACTION)
                  ||
                  V
The ActionName & Controller name will be taken from HttpRequest.Url object (Simple parsing)
                  ||
                  V
Create Controller: Create a new instance of the Controller (A simple csharp class) using 'Activator' class
                  ||
                  V
Call Action:Call function of that class using 'InvokeMember'



 
Lets view the code:

The handler:

public class SimpleHandler : IHttpHandler
{
        private string _controllerName { get; set; }
        private string _actionName { get; set; }

        #region IHttpHandler Members

        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            try
            {

       
       //SET THE CONTROLLER AND ACTION NAMES

             string[] array = context.Request.Url.AbsoluteUri.Split('/');
            _controllerName = array[4];
            _actionName = array[5];

            
    //DECLARE THE BASE CONTROLLER OBJECT
                MyBaseController myBaseController = null;
           
               
//Load assembly (This assembly has all the Controllers + Actions + BaseController)
                Assembly sampleAssembly = Assembly.Load
                    ("MyAssembly", Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

               
                try
                {
                   
//Here I decide ..with what 'Type' have to instantiate my
'MyBaseController' object depending
                    //upon what controller name user passed.
                    //So instead of using a hardcoded thing like var x=new y();
                    //I am dynamically generating the instance depending upon what user passed in url as controller name :)


                   Type typeToCreate = sampleAssembly.GetTypes().Where(t => t.Name == _controllerName).First();

                    if (typeToCreate != null)
                    {
                      
  //Create instance from Type
                        object controllerInstance= Activator.CreateInstance(typeToCreate);
                        myBaseController = (MyBaseController)controllerInstance;


 
                       //OnActionExecuting_Custom is virtual so if you overide it in your controller...so yours will be called.
                       myBaseController .
OnActionExecuting_Custom();
 

                         //Call the Action using InvokeMember.(Since instance was dynamically created so i cant use the standard  obj.Function() kinda technique...so use InvlokeMember instead of that :))

                        object result = obj.GetType().InvokeMember(_actionName, BindingFlags.InvokeMethod, null, obj, null);

                        HttpResponse response = context.Response;
                        response.Write(result.ToString());
                    }
                    else
                    {
                        throw new Exception("Invalid path");
                    }
                }
                catch(Exception ex)
                {
                    throw new Exception("Invalid path");
                }

            }
            catch (Exception ex)
            {
                HttpResponse response = context.Response;
                response.Write(ex.Message);
              
            }


        }

        #endregion

    }


 


 //This is the base class from which all the Controllers will be inheriting
//This is basically the substitute for the 'Controller' base class which ASP.NET provides.


  public abstract class MyCustomController
 {
        public virtual void OnActionExecuting_Custom()
        {
         
        }

        public virtual void AfterActionExecuting_Custom()
        {

        }

 }



//Sample Controller created which inherits from
//MyBaseController instead of inheriting from Controller


   public class Feeds :
MyCustomController     {
        public string News()
        {
            return "Breaking NEWS !!! :)";
        }


        public string CoolMessages()
        {
            return "Do or Die :)";
        }


        public override void OnActionExecutings()
        {
            string temp = "I have overidden it";
        }


    }