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
}