我们公司正在为我们的产品开发 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 进行多参数路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!