2012-08-06 78 views
2

对于一个项目,我必须(不幸地)匹配一些确切的URL。ASP.Net MVC3:创建自定义URL,但不包含确切的控制器名称

所以我认为这不会是一个问题,我可以使用“MapRoute”来匹配网址与所需的控制器。但我无法让它工作。

我已经映射此网址:

http://{Host}/opc/public-documents/index.html 

Area: opc 
Controller: Documents 
Action: Index 

另一个例子是映射

http://{Host}/opc/public-documents/{year}/index.html 

Area: opc 
Controller: Documents 
Action:DisplayByYear 
Year(Parameter): {year} 

我想这一点,whitout成功,在我区(ocpAreaRegistration.cs):

context.MapRoute("DocumentsIndex", "opc/public-documents/index.html", 
    new {area="opc", controller = "Documents", action = "Index"}); 
context.MapRoute("DocumentsDisplayByYear", "opc/public-documents/{year}/index.html", 
    new {area="opc", controller = "Documents", action = "Action:DisplayByYear"}); 

但我得到了一些404错误:(当我试图访问它。我究竟做错了什么?

+0

ocpAreaRegistration何时被调用?它应该由global.asax.cs中的'RegisterRoutes'调用 – podiluska 2012-08-06 12:25:40

+0

不能为两个不同的路由使用相同的maproute id。在实际的代码中是这样吗? – cellik 2012-08-06 12:28:04

+0

@cellik对不起,我只是在示例中,坏的复制粘贴 – J4N 2012-08-06 12:28:54

回答

2

我不知道为什么你需要做到这一点(我只能假设你正在从一个传统的应用程序推出),但是这是为我工作:

opcAreaRegistration.cs:

public override void RegisterArea(AreaRegistrationContext context) 
{ 
    context.MapRoute(
     "opc_public_year_docs", 
     "opc/public-documents/{year}/index.html", 
     new { controller = "Documents", action = "DisplayByYear" } 
    ); 

    context.MapRoute(
     "opc_public_docs", 
     "opc/public-documents/index.html", 
     new { controller = "Documents", action = "Index" } 
    ); 

    context.MapRoute(
     "opc_default", 
     "opc/{controller}/{action}/{id}", 
     new { action = "Index", id = UrlParameter.Optional } 
    ); 
} 

控制器:

public class DocumentsController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult DisplayByYear(int year) 
    { 
     return View(year); 
    } 
} 

确保将这些路由在区域的路由文件,而不是Global.asax的,你应该是好去。

+1

哎哟,我不知道ordre有一些重要性,你的代码指出了它!我的自定义规则之前有默认路由(opc_default))。 谢谢!(原因是:这是一个联邦网站,他们在两个月的时间里讨论了定义url结构的问题,所以我必须使用他们的URL。 – J4N 2012-08-06 12:39:24

+0

@ J4N不客气,这听起来很有趣。至于路由,它确实从具体到一般,因为你已经注意到了。如果你对这种情况的例子感兴趣,我发布了一个[答案](http://stackoverflow.com/questions/11819989/parameters-in-routing-do-not-work-mvc-3/11820201 #11820201)昨天的一个类似的问题,这将有望帮助。 – 2012-08-06 12:42:48

相关问题