【问题标题】:ASP.Net MVC3: Create custom URL without having the exact controller name in itASP.Net MVC3:创建自定义 URL 而不包含确切的控制器名称
【发布时间】:2012-08-03 09:54:12
【问题描述】:

对于一个项目,我必须(不幸地)匹配一些确切的 url。

所以我认为这不会有问题,我可以使用“MapRoute”,将 url 与所需的控制器匹配。但我不能让它工作。

我必须映射这个 URL:

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}

我在我所在的地区尝试了这个,但没有成功(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 错误 :(。我做错了什么?

【问题讨论】:

  • ocpAreaRegistration 什么时候被调用?它应该由 global.asax.cs 中的RegisterRoutes 调用
  • 您不能对两条不同的路线使用相同的 maproute id。实际代码中是这样的吗?
  • @cellik 对不起,mapRoute Id,它只在示例中,错误的复制粘贴
  • @podiluska 因为它是为区域opc注册默认路由的文件(由VS2010在创建区域时创建),我想它应该已经被调用了。我尝试将这段代码直接放在 Global.asax.cs 中,但没有任何改变。

标签: asp.net-mvc routes friendly-url


【解决方案1】:

我不确定您为什么需要这样做(我只能假设您来自旧版应用程序),但这对我有用:

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 中,这样就可以了。

【讨论】:

  • 哎呀,我不知道顺序有什么重要性,你的代码指出了这一点!我在自定义规则之前有默认路由(opc_default))。谢谢!(原因:这是一个联邦网站,他们在大约两个月的时间里讨论了如何定义 url 结构,所以我必须使用他们的 URL。
  • @J4N 不客气,这听起来很有趣。 :) 至于路由,它确实从特定到一般,正如您已经注意到的那样。如果您对为什么会这样的示例感兴趣,我昨天在类似问题上发布了 answer,希望对您有所帮助。
猜你喜欢
  • 2012-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多