Skip to main content
 首页 » 编程设计

c#之了解 ASP.NET MVC 中的路由

2024年02月23日19itcoder

我正在努力思考 ASP.NET MVC 实现路由的方式。

据我目前的理解,我的路由字符串似乎有一个“{controller}”和“{action}”,否则它不起作用?

我将如何定义使用 SearchController 和 Search 操作同时采用 SearchKeywords 和 SearchCaseSensitive 参数的路由有以下网址吗?

domain/SearchKeywords/CaseSensitive 

更简单的是,如何将 domain 映射到 Controller SearchController 和 Search?

请您参考如下方法:

From what is my current understanding, it seems my route string much have a "{controller}" and "{action}", otherwise it doesn't work?

Controller 和操作 token 的值是必需的。您有 2 个选项来提供值:

1) 在 URL 模板上使用 {controller} 和 {action} 标记。例如:

routes.MapRoute(null, "{controller}/{action}"); 

2) Controller 和 Action 使用默认值。例如:

routes.MapRoute(null, "some-url", 
   new { controller = "Search", action = "Search" } 
); 

How would I define the route that using a SearchController and Search action taking both SearchKeywords and SearchCaseSensitive arguments had the following URL?

domain/SearchKeywords/CaseSensitive

路由系统不考虑 URL 主机(或域),只考虑应用程序相对路径。你可以这样做:

routes.MapRoute(null, "{SearchKeywords}/{CaseSensitive}", 
   new { controller = "Search", action = "Search" } 
); 

您还可以为 SearchKeywords 和 CaseSensitive 提供默认值,如果您想让它们中的任何一个成为可选的。