Search code examples
c#asp.netasp.net-mvcwebformsasp.net-routing

Adding MVC4 to Webforms Application - Routing Not Working


I'm trying to add MVC 4 into an existing webforms project. I followed this guide: https://www.packtpub.com/books/content/mixing-aspnet-webforms-and-aspnet-mvc

After adding to the web.config:

<add assembly="System.Core, Version=3.5.0.0, Culture=neutral,PublicKeyToken=B77A5C561934E089"/>
      <add assembly="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

I made a Controller (HomeController.cs) in the Controllers folder:

using System.Web.Mvc;

namespace MixingBothWorldsExample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "This is ASP.NET MVC!";
            return View();
        }
    }
}

I then added my view at Views/Home/index.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs"    Inherits="MixingBothWorldsExample.Views.Home.Index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <div>
        <h1><%=Html.Encode(ViewData["Message"]) %></h1>
    </div>
</body>

Then added my route:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}

public static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
    routes.MapRoute("Test", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

For some reason, everything in my existing webforms project works just fine (including PageRoutes), however /home/index gives me a 404, implying that it's not even routing to the controller.

Anyone have any ideas?


Solution

  • Ultimately, I ended taking my existing website and adding it to an MVC application, rather than going the other way around. The routing worked just fine then.