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

标签 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" }
);

Controller 看起来像这样:

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

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

The parameters dictionary contains a null entry for parameter....

我想避免传递一个未使用的参数来绕过路由规则,例如 /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 )
            { ... }

最佳答案

我没有测试它,但您可以在操作的 Route 属性上使用约束。例如,您的路由 url:

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

(使用 Route 属性,您也可以修改路由 url,基本上可以解决您的问题而无需担心约束)

关于 this page你可以找到更多(它是关于 Web Api,但路由过程应该是相同的)。

实际上还有另一种方法可以在路由 url 上设置约束:MapRoute 中的 constraints 键。

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

您也可以在其中使用正则表达式。

关于c# - 两个具有不同数据类型的 MapRoutes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45925967/

相关文章:

c# - ASP.NET 多线程 & "thread has already entered the lock"

html - 布局/HTML 中的 MVC 4 错误

asp.net - 如何修复为 Microsoft.aspnetcore.razor.language 检测到的版本冲突?

c# - 什么是 "Async Pinned Handle"?

c# - IIS 7.5 asp.net 应用程序是否可以在 HTTPS 上运行,而不授予 ApplicationPool-Identity 对证书存储的读取权限?

javascript - Ajax 无法将表单 ID 发送到 MVC Controller

c# - 对于特定属性,您如何在 ModelState 中获取错误?

c# - 如何替换某些段的值以保留其他段的值?

c# - 如何在 C# 中有效地返回 SortedList<> 中的第一项和最后一项?

c# - 留在移动平台上