Integrating ASP.NET MVC 4 into Existing Web Forms Applications

By September 27, 2012ASP.NET, MVC

So you have seen the light and ready to make the jump into ASP.NET MVC. But wait! You are not ready to migrate a million lines of code from your legacy Web Forms application? No problem. You can easily integrate MVC 4 into your existing Web Forms application and gradually phase out the legacy stuff over time.

There are many articles and blog posts about this topic. However, most are outdated or take the loooong way. I have a simple, clean solution for you! Here it goes:

  1. Upgrade your Web Forms application to .NET 4 (and Visual Studio 2012 if you want)
  2. Install NuGet packages: MVC 4 and Web API  
  3. Add this to <ProjectTypeGuids> in your .csproj file: {E3E379DF-F4C6-4180-9B81-6769533ABE47};. This will add MVC goodies to your Visual Studio such as right-click > Add Controllers / Views.
  4. Create App_Start, Controllers, Models, Views folders in the root of your application
  5. Right-click on the Controllers folder and add “HomeController”
  6. Right-click on “Index” in the “HomeController” and “Add a view”
  7. Create the folder ~/Controllers/Api
  8. Add a new item and choose WebAPI Controller Class (call it HomeController if you like)
  9. Create a blank MVC 4 Empty project in a separate Visual Studio instance
  10. Copy FilterConfig.cs, RouteConfig.cs and WebApiConfig.cs from ~/App_Start to your ~/App_Start folder you created in the previous step. Be sure to update the namespace to be consistent with your other namespacing. Also you can leave out BundleConfig.cs if you like because you should be using JavaScript AMD instead of bundling.
  11. Add the following ignore rule to the ~/App_Start/RouteConfig.cs: routes.IgnoreRoute(“{resource}.aspx/{*pathInfo}”);
  12. In your Global.asax, merge the following code: 
    void Application_Start(object sender, EventArgs e)
    protected void RegisterRoutes()

  13. Copy the ~/Views folder from your blank MVC 4 application you created in the previous step. The web.config content will give you the namespaces and intellisense you need in Razor pages.
  14. Build then fire up your browser and go to http://yourapp/home/index and http://yourapp/api/home. You should see the controller view and serialized data respectively.
That’s it! Don’t you feel better now?

Happy Coding!!
The following two tabs change content below.