asp.net mvc 4中的自定义路由

时间:2014-03-30 21:35:51

标签: asp.net-mvc asp.net-mvc-routing

我正在制作一个小项目,其中有一个页面,显示可供下载的应用程序列表。我在RouteConfig.cs中的路由如下所示:

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "ViewApplication",
            url: "View/{applicationname}",
            defaults: new { controller = "View", action = "ViewApplication"}
        );

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

我的控制器看起来像这样:

public class ViewController : Controller
{
    public ActionResult ViewApplication(string applicationname)
    {
        return View();
    }
}

但每当我尝试导航到localhost:50788 / View / A610723时,它都会失败,并且URL会更改为localhost:50788 /?并留在主页上。

我看过这个问题 MVC 4: Custom Routes 它与我想要做的几乎完全相同,他们使用beername作为字符串,但我的工作不起作用。

有没有我错过的东西?

由于

1 个答案:

答案 0 :(得分:1)

您的解决方案似乎是正确的。你确定你的错误不在其他地方吗?

以下是此链接的一个小例子:

http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs

它看起来与您的解决方案完全相同。

using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1 {
public class MvcApplication : System.Web.HttpApplication {

    public static void RegisterRoutes(RouteCollection routes) { 

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute( 
          "Blog", // Route name 
          "Archive/{entryDate}", // URL with parameters
           new { controller = "Archive", action = "Entry" } // Parameter defaults 
           );

           routes.MapRoute( "Default", // Route name 
           "{controller}/{action}/{id}", // URL with parameters
           new { controller = "Home", action = "Index", id = "" } // Parameter defaults
           ); 
    } 

    protected void Application_Start() {

          RegisterRoutes(RouteTable.Routes);

    } 
  }
}

这是控制器:

 using System; using System.Web.Mvc;

 namespace MvcApplication1.Controllers { 
 public class ArchiveController : Controller { 

     public string Entry(DateTime entryDate) { 
          return "You requested the entry from " + entryDate.ToString(); 
     }
   } 
 }