Over a million developers have joined DZone.

MVC–Showing a setup screen on the first run

DZone's Guide to

MVC–Showing a setup screen on the first run

· ·
Free Resource

Recently, I participated in a project where I helped to build a website in Orchard. One of the things that I admire (and there are many) about Orchard is the setup screen that appears the first time you run the site. It’s a nice touch and really makes the site easy to configure. No need to tweak a web.config, create a database or read a 20 page setup guide on how to get started. You just fill out the form and the site is ready…

Of course, I wanted to build something similar for my open source project WeBlog. First, I tried to reverse engineer the orchard code. However, orchard uses a lot of dynamic types and things are heavily abstracted so it was hard to re-use their code for my purposes. Next, I tried to Google for a solution but the only thing I could find was this stack overflow post.

My first thought was to create a base controller class and override the OnActionExecuting method. In that method I could force a redirect if the site was not configured yet. However, I abandoned this strategy because at this point in the process the wrong controller has already been created (the one assigned to the default route) and I basically have to cancel the previous request and redirect. Therefore, I decided to use a custom controller factory instead. This way I can intercept which controller and action should be fired if the site has not been configured yet much earlier in the process. Here is what I came up with:

public class WeBlogControllerFactory : DefaultControllerFactory
    public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        if (!SiteManager.Any())
            requestContext.RouteData.Values["action"] = "Index";
            requestContext.RouteData.Values["controller"] = "Setup";
            return base.CreateController(requestContext, "Setup");

        return base.CreateController(requestContext, controllerName);

Finally, you will need to register your custom controller factory, just add this line to the application_start method in the global.asax:

ControllerBuilder.Current.SetControllerFactory(new WeBlogControllerFactory());

So now when my application runs the first time I get the setup screen. Sweet!


The code can be viewed here. Please leave a comment if you have an alternative solution.



Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}