Mixing ASP.NET MVC and Webforms

http://www.aspnetmvcninja.com/general/mixing-asp-net-mvc-and-webforms

 

Do you have a existing ASP.NET Web Forms project that you would love to migrate to ASP.NET MVC but can’t because you have so much invested in it? I know I did and I’m sure many of you do. The good news is that ASP.NET MVC and ASP.NET Web Forms are compatible allowing you to mix ASP.NET MVC and ASP.NET Webforms in the same project. In this ASP.NET MVC tutorial I’ll show you how to add support for ASP.NET MVC to an existing ASP.NET Web Forms project.

The advantage of adding ASP.NET MVC to an existing ASP.NET Web Forms application is that you can keep your existing code and write all new code using ASP.NET MVC.

So how do you do it? First you need to add references to the following assemblies:

  • System.Web.Abstractions
  • System.Web.Extensions
  • System.Web.Mvc
  • System.Web.Routing

Once you have added those you need the special ASP.NET MVC folders and you probably want a couple of files that an empty ASP.NET MVC application gets by default. The easiest way to do this is to create an empty ASP.NET MVC project then copy the following folders with their contents and sub folders into your existing ASP.NET Web Forms project

  • Content
  • Controllers
  • Models
  • Scripts
  • Views

This gives you all of the special folders and files that you need.

You then need to either create a new Global.asax file or modify your existing one. If you are editing an existing one then you need to add the following to your Global class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}
 
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
}

All of that is from the standard Global.asax file for a new ASP.NET MVC 3 application except for the following line which stops routing of any .aspx URL.

1
routes.Ignore("{resource}.aspx/{*pathinfo}");

You also need to add the following code to your Application_Start() method in Global.

1
2
3
4
AreaRegistration.RegisterAllAreas();
 
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);

Finally you need to make some changes to your Web.config. As with the previous changes it’s best to copy the missing settings from an empty ASP.NET MVC application. In my case I had to add the following to support ASP.NET MVC 3 with the ASPX view engine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<appSettings>
  <add key="ClientValidationEnabled" value="true"/>
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
 
</appSettings>
<system.web>
  <compilation debug="true" targetFramework="4.0">
    <assemblies>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </assemblies>
  </compilation>
 
  <authentication mode="Forms">
    <forms loginUrl="~/Account/LogOn" timeout="2880" />
  </authentication>
 
  <pages>
    <namespaces>
      <add namespace="System.Web.Helpers" />
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="System.Web.WebPages"/>
    </namespaces>
  </pages>
</system.web>
 
<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

You can now create a test controller to make sure that you’ve got everything setup correctly. I used the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Example.Controllers
{
    public class HelloController : Controller
    {
        public string Index()
        {
            return "Hello World!!";
        }
    }
}

Now run your application and go to /hello. If it works you should see the response Hello World!!

UPDATE 2011-02-28:
After making these changes Visual Studio still didn’t treat the ASP.NET Web Forms project as a ASP.NET MVC project. To get Visual Studio 2010 to treat the ASP.NET Web Forms project like an ASP.NET MVC project I needed to add a GUID to ProjectTypeGuids in my projects .web file. The exact GUID depends on the version of ASP.NET MVC you are using.

ASP.NET MVC 3 – {E53F8FEA-EAE0-44A6-8774-FFD645390401}
ASP.NET MVC 2 – {F85E285D-A4E0-4152-9332-AB1D724D3325}

For ASP.NET MVC 3 my file has the line:

1
<ProjectTypeGuids>{E53F8FEA-EAE0-44A6-8774-FFD645390401};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>;

Once that was done Visual Studio behaved properly and displayed all of the ASP.NET MVC specific items in its context menus.

PS: If anyone has the GUID for ASP.NET MVC 1 then please send it to me and I’ll add it above.

posted @ 2012-02-23 14:44  如实知  阅读(239)  评论(0编辑  收藏  举报