Model View Controller In ASP.Net

time to read 7 min | 1326 words

As it turned out, it takes 20 lines of code to add MVC to ASP.Net*:

public class ModelViewControllerHandlerFactory : IHttpHandlerFactory

{

    public IHttpHandler GetHandler(HttpContext context,

                string requestType, string url, string pathTranslated)

    {

        string path = context.Request.Path;

        IController controller = Container.Current.Resolve<IController>(path);

        controller.Process(context);

        context.Items[controller.View] = controller;

        return controller.View;

    }

 

    public void ReleaseHandler(IHttpHandler handler)

    {

        IController controller = HttpContext.Current.Items[handler] as IController;

        if (controller == null)

            return;

        controller.End();

        Container.Current.Release(controller);

    }

}

This relies on Windsor Container to handle the mapping from a request path to the appropriate controller, and then it will wire up the view defined for the controller, as well as anything else needed to handle the request. The controller then does the work, pushing all the values to the view, and then the view is run normally.

This maintain a strict seperation of a concerns between the controller and the view, but still allows you to do all the usual ASP.Net magic.

* Okay, I lie. This is the bare minimum that you have, which is usually not something that you would like to do. Since it will force you to map each url in the application. Usually you will want to be a little smarter about it.