MVC附加自定义路由

时间:2016-02-03 11:58:26

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

我想在我的MVC应用程序中实现自定义路由,但我无法让它工作。我想在创建MVC应用程序时保持指定的存在默认路由。

我希望有效的路线应如下所示:

  

默认:/ {controller} / {action} / {id}

     

新自定义:/ {controller} / {appid} / {action} / {id}

使用自定义域,我将在每个请求中传递appid,但{id}应该是可选的。因此,路线定义如下:

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

        routes.MapRoute(
            name: "NewPackageRoute",
            url: "{controller}/{appid}/{action}/{id}",
            defaults: new { controller = "apps", appid = "00000000000000000000", action = "Index", id = UrlParameter.Optional }
        );

在AppsController上,我有一个操作方法索引:

public ActionResult Index(string appid, string id)

如果我提供了id参数,则按预期命中此操作方法。我期望如果没有提供{id}参数也会调用此方法,从而将id参数保留为null。然而,这不会发生。

我应该如何定义不同的路线?我是否应该使用AttributeRouting来实现我的目标?

我也许应该添加......如果我在Apps控制器上调用搜索操作,我就可以开始操作了。这将通过默认路线发生......

希望我有足够的信息......

1 个答案:

答案 0 :(得分:0)

哦,我的,但我想我应该在发布之前尝试过。我把这个问题留了一天,现在我没有任何努力就让它工作了......

谢谢@StephenMuecke。你确实指出了我忘记的路线的顺序。我最初玩过这个订单,但是在那个时候我在路线定义中遇到了其他问题导致它无法正常工作。

我添加的所有内容都是对appid路由值的长度检查,它正在运行......我的路由现在定义如下:

routes.MapRoute(
    name: "NewPackageRoute",
    url: "apps/{appid}/{action}/{id}",
    defaults: new { controller = "Apps", action = "Index", id = UrlParameter.Optional }, 
    constraints: new { appid = @"^[a-zA-Z0-9]{20}" }
);

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