Click here to Skip to main content
Click here to Skip to main content

Using ASP.NET MVC Without Creating Controllers for Each View

, 23 May 2014
Rate this:
Please Sign up or sign in to vote.
Using ASP.NET MVC without creating controllers for each view

Introduction

Microsoft ASP.NET MVC is arguably one of the most flexible frameworks for building modern web applications. One of the things that I've noticed over the last couple of years is that with many AJAX applications using Restful web service, many MVC controllers are now almost redundant.

Background

Using the default MVC HTTP handler means that regardless of whether you actually need server-side code for rendering each view, you must have a corresponding controller.

ASP.NET MVC Default Routing Behaviour

In many cases, these controllers have a single action (e.g. Index) which simply returns the view. This seems inefficient and adds to the maintenance cost of the application.

So how can we get around this? Wouldn't it be great if we could just have a single re-usable controller with a single action instead of creating multiple copies of the same thing? The good news is that it's easy with MVC!

ASP.NET MVC Modified Routing Behaviour

Create a Custom HTTP Handler

The first thing that we need to create is a custom HTTP handler [ControllerLessHttpHandler.cs]. This will look for a controller relevant to the view being requested; if it finds one, then it will work in the usual way. This means that if you need a controller for specific pages, you can still add them.

If it doesn't find a controller for the view, it will re-route the request to a re-usable controller-less view controller (we'll get to that bit later on).

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

/// <summary>
/// The ControllerLessHttpHandler class.
/// </summary>
public class ControllerLessHttpHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState, IRouteHandler
{
    /// <summary>
    /// The requestContext field.
    /// </summary>
    private readonly RequestContext _requestContext;

    /// <summary>
    /// Initializes a new instance of the <see cref="ControllerLessHttpHandler"/> class.
    /// </summary>
    /// <param name="requestContext">The request context.</param>
    public ControllerLessHttpHandler(RequestContext requestContext)
    {
        _requestContext = requestContext;
    }

    /// <summary>
    /// Gets a value indicating whether another request can use the 
    /// <see cref="T:System.Web.IHttpHandler" /> instance.
    /// </summary>
    /// <returns>true if the <see cref="T:System.Web.IHttpHandler" /> 
    /// instance is reusable; otherwise, false.</returns>
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

    /// <summary>
    /// Process the current HTTP request.
    /// </summary>
    /// <param name="httpContext">The HttpContext containing the request.</param>
    public void ProcessRequest(HttpContext httpContext)
    {
        var controller = _requestContext.RouteData.GetRequiredString("controller");
        var action = string.Empty;

        if (_requestContext.RouteData.Values["action"] != null)
        {
            action = _requestContext.RouteData.Values["action"].ToString();
        }

        if (action != string.Empty)
        {
            IController viewController = null;
            IControllerFactory viewControllerFactory = null;

            try
            {
                viewControllerFactory = ControllerBuilder.Current.GetControllerFactory();

                try
                {
                    viewController = viewControllerFactory.CreateController(_requestContext, controller);
                }
                catch
                {
                    _requestContext.RouteData.Values["ctrl"] = controller;
                    _requestContext.RouteData.Values["x-ctrl"] = controller;
                    _requestContext.RouteData.Values["action"] = "Index";
                    _requestContext.RouteData.Values["x-action"] = action;

                    controller = "ControllerLess";
                    viewController = viewControllerFactory.CreateController(_requestContext, controller);
                }

                if (viewController != null)
                {
                    viewController.Execute(_requestContext);
                }
            }
            finally
            {
                if (viewControllerFactory != null)
                {
                    viewControllerFactory.ReleaseController(viewController);
                }
            }
        }
    }

    /// <summary>
    /// Provides the object that processes the request.
    /// </summary>
    /// <param name="requestContext">
    /// An object that encapsulates information about the request.</param>
    /// <returns>An object that processes the request.</returns>
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        throw new NotImplementedException();
    }
}

Create the Route Handler

Next, we need to create a custom route handler [ControllerLessRouteHandler.cs] to let MVC know which HTTP handler to use to process each request.

using System.Web;
using System.Web.Routing;

/// <summary>
/// The ControllerLessRouteHandler class.
/// </summary>
public class ControllerLessRouteHandler : IRouteHandler
{
    /// <summary>
    /// Provides the object that processes the request.
    /// </summary>
    /// <param name="requestContext">An object that encapsulates information about the request.</param>
    /// <returns>An object that processes the request.</returns>
    IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
    {
        return new ControllerLessHttpHandler(requestContext);
    }
}

Update the MVC Route Configuration

Once all this is in place, we can configure the MVC routes [RouteConfig.cs] to use the custom route handler.

using System.Web.Mvc;
using System.Web.Routing;

/// <summary>
/// The RouteConfig class.
/// </summary>
public class RouteConfig
{
    /// <summary>
    /// Registers the routes.
    /// </summary>
    /// <param name="routes">The routes.</param>
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        var route = new Route(
                    "{controller}/{action}/{id}",
                    new RouteValueDictionary(new { controller = "Home", 
                    action = "Index", id = UrlParameter.Optional }),
                    new ControllerLessRouteHandler());

        routes.Add(route);
    }
}

Create the Custom Controller

Finally, we can add the custom view controller that the requests will be routed through [ControllerLessController.cs].

using System.Web.Mvc;

/// <summary>
/// The ControllerLessController class.
/// </summary>
public class ControllerLessController : Controller
{
    /// <summary>
    /// Provides the default view controller.
    /// </summary>
    /// <returns>The requested view.</returns>
    public ActionResult Index()
    {
        var controller = RouteData.Values["x-ctrl"].ToString();
        var action = RouteData.Values["x-action"].ToString();
        var path = string.Format("~/Views/{0}/{1}.cshtml", controller, action);
        return View(path);
    }
}

Now give it a try. Simply add a view without a corresponding controller, start up your application and navigate to the view in your browser.

You can now add as many views as you like, without needing to add any more controllers. And if you need a controller for a specific view, just add it in the normal way and it will work as expected.

NuGet

A NuGet package supporting both C# and VB.NET views and with more configuration options is available at https://www.nuget.org/packages/ControllerLess.

GitHub

The source code for the NuGet package can be found at https://github.com/brentj73/ControllerLess.

History

Originally published by Brent Jenkins at http://www.anterec.co.uk/articles/using-aspnet-mvc-5-without-creating-controllers-for-each-view/.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Brent Jenkins
Software Developer Anterec
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
SuggestionMore powerful PinmemberWladis4-Jun-14 23:25 
GeneralRe: More powerful PinmemberBrent Jenkins4-Jun-14 23:39 
GeneralRe: More powerful PinmemberWladis4-Jun-14 23:52 
GeneralRe: More powerful PinmemberBrent Jenkins4-Jun-14 23:56 
GeneralRe: More powerful PinmemberWladis5-Jun-14 0:34 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 0:48 
GeneralRe: More powerful PinmemberWladis5-Jun-14 0:56 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 0:58 
GeneralRe: More powerful PinmemberWladis5-Jun-14 1:02 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 1:05 
GeneralRe: More powerful PinmemberWladis5-Jun-14 1:11 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 1:18 
GeneralRe: More powerful PinmemberWladis5-Jun-14 2:00 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 2:09 
GeneralRe: More powerful PinmemberWladis5-Jun-14 2:29 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 2:39 
AnswerRe: More powerful [modified] PinmemberWladis5-Jun-14 3:02 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 3:17 
AnswerRe: More powerful PinmemberWladis5-Jun-14 3:24 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 3:28 
GeneralRe: More powerful PinmemberWladis5-Jun-14 3:34 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 3:44 
GeneralRe: More powerful PinmemberWladis5-Jun-14 4:19 
GeneralRe: More powerful PinmemberBrent Jenkins5-Jun-14 4:21 
GeneralRe: More powerful PinmemberWladis5-Jun-14 4:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 23 May 2014
Article Copyright 2014 by Brent Jenkins
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid