Routing with Multiple Parameters using ASP.NET MVC(使用 ASP.NET MVC 进行多参数路由)
问题描述
我们公司正在为我们的产品开发 API,我们正在考虑使用 ASP.NET MVC.在设计 API 时,我们决定使用如下调用,让用户从 API 请求 XML 格式的信息:
Our company is developing an API for our products and we are thinking about using ASP.NET MVC. While designing our API, we decided to use calls like the one below for the user to request information from the API in XML format:
http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&api_key=b25b959554ed76058ac220b7b2e0a026
如您所见,传递了多个参数(即 artist
和 api_key
).在 ASP.NET MVC 中,artist
将是 controller
,getImages
是动作,但是如何将多个参数传递给动作?
As you can see, multiple parameters are passed (i.e. artist
and api_key
). In ASP.NET MVC, artist
would be the controller
, getImages
the action, but how would I pass multiple parameters to the action?
这甚至可以使用上面的格式吗?
Is this even possible using the format above?
推荐答案
在 MVC 中直接支持参数,只需将参数添加到您的操作方法中即可.给定如下操作:
Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:
public ActionResult GetImages(string artistName, string apiKey)
当给定如下 URL 时,MVC 将自动填充参数:
MVC will auto-populate the parameters when given a URL like:
/Artist/GetImages/?artistName=cher&apiKey=XXX
另一种特殊情况是名为id"的参数.任何名为 ID 的参数都可以放入路径而不是查询字符串中,例如:
One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:
public ActionResult GetImages(string id, string apiKey)
将使用如下所示的 URL 正确填充:
would be populated correctly with a URL like the following:
/Artist/GetImages/cher?apiKey=XXX
另外,如果你有更复杂的场景,你可以自定义MVC用来定位动作的路由规则.您的 global.asax 文件包含可以自定义的路由规则.默认情况下,规则如下所示:
In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
如果你想支持像
/Artist/GetImages/cher/api-key
您可以添加如下路线:
routes.MapRoute(
"ArtistImages", // Route name
"{controller}/{action}/{artistName}/{apikey}", // URL with parameters
new { controller = "Home", action = "Index", artistName = "", apikey = "" } // Parameter defaults
);
和上面第一个例子一样的方法.
and a method like the first example above.
这篇关于使用 ASP.NET MVC 进行多参数路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ASP.NET MVC 进行多参数路由
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01