将MVC4添加到Webforms应用程序 - 路由不起作用

时间:2014-10-17 20:34:17

标签: c# asp.net asp.net-mvc webforms asp.net-routing

我正在尝试将MVC 4添加到现有的webforms项目中。我遵循了这个指南:https://www.packtpub.com/books/content/mixing-aspnet-webforms-and-aspnet-mvc

添加到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"/>

我在Controllers文件夹中创建了一个Controller(HomeController.cs):

using System.Web.Mvc;

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

然后我在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>

然后添加了我的路线:

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 });
}

出于某种原因,我现有的webforms项目中的所有内容都运行得很好(包括PageRoutes),但是/ home / index给了我404,这意味着它甚至没有路由到控制器。

有人有什么想法吗?

4 个答案:

答案 0 :(得分:1)

最终,我结束了我现有的网站并将其添加到MVC应用程序,而不是反过来。路由工作正常。

答案 1 :(得分:0)

试试这个,

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

答案 2 :(得分:0)

我认为你可能需要在HomeController的Index方法中添加一个id参数。即使它是可选的,路由器也在寻找一种带有id的方法。

编辑:对不起,我不知道我在想什么。如您所引用的文章所示,这是错误的。

答案 3 :(得分:0)

您可以尝试以下路由规则吗?这适用于MVC4项目。这定义了当您导航到某个URL和端口(例如locallhost)时将加载的默认页面:4897

public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

   routes.MapRoute(
       name: "Default",
       url: "{controller}/{action}/{id}",
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );
}