两个具有不同数据类型的MapRoutes

时间:2017-08-28 19:18:42

标签: c# asp.net-mvc

我需要进行以下C#MVC调用,例如:

/ SomeController / ActionOne / 1/2/3
/ SomeController / ActionTwo / 1/2 / ASTRING

以下是我的路线图:

routes.MapRoute (
                name: "One",
                url: "SomeController/{action}/{intId1}/{intId2}/{intId3}",
                defaults: new { controller = "SomeController", action = "ActionOne" }
);

routes.MapRoute (
                name: "Two",
                url: "SomeController/{action}/{intId1}/{intId2}/{string1}",
                defaults: new { controller = "SomeController", action = "ActionTwo" }
);

并且控制器看起来像这样:

public ActionResult ActionOne ( int intId1, int intId2, int intId3 )
            { ... }
public ActionResult ActionTwo ( int intId1, int intId2, string string1 )
            { ... }

当我使用URL / SomeController / ActionTwo / 1/2 / astring 时,这会产生

参数字典包含参数....的空条目。 / BLOCKQUOTE>

我想避免仅仅为了绕过路由规则传递一个未使用的参数,例如 / SomeController / ActionTwo / 1/2 // astring

public ActionResult ActionOne ( int intId1, int intId2, int? intId3, string? string1 )
            { ... }
public ActionResult ActionTwo ( int intId1, int intId2, int? intId3, string? string1 )
            { ... }

1 个答案:

答案 0 :(得分:2)

我没有对其进行测试,但您可以对动作的Route属性使用约束。例如,使用您的路由网址:

[Route("SomeController/{action}/{intId1}/{intId2}/{intId3:int}]

(使用Route属性,您也可以修改路由网址,基本上解决您的问题,而不必担心限制条件)

this page上,您可以找到更多内容(关于Web Api,但路由过程应该相同)。

实际上还有另一种方法可以为您的路由网址设置约束:constraints中的MapRoute密钥。

routes.MapRoute(
name: "One",
url: "SomeController/{action}/{intId1}/{intId2}/{intId3}",
defaults: new { controller = "SomeController", action = "ActionOne" }
constraints: new{intId3=@"\d+"} 
);

你也可以使用正则表达式。