Cod*_*nts 133 .net c# asp.net-mvc routing
我们公司正在为我们的产品开发API,我们正在考虑使用ASP.NET MVC.在设计我们的API时,我们决定使用下面的调用来让用户以XML格式从API请求信息:
如您所见,传递了多个参数(即artist
和api_key
).在ASP.NET MVC,artist
将是controller
,getImages
在行动,但我会如何将多个参数传递给动作?
这甚至可以使用上面的格式吗?
Rya*_*ner 274
只需在操作方法中添加参数,即可在MVC中直接支持参数.给出如下行动:
public ActionResult GetImages(string artistName, string apiKey)
Run Code Online (Sandbox Code Playgroud)
当给定如下URL的URL时,MVC将自动填充参数:
/Artist/GetImages/?artistName=cher&apiKey=XXX
Run Code Online (Sandbox Code Playgroud)
另一个特殊情况是名为"id"的参数.任何名为ID的参数都可以放入路径而不是查询字符串,如下所示:
public ActionResult GetImages(string id, string apiKey)
Run Code Online (Sandbox Code Playgroud)
将使用如下所示的URL正确填充:
/Artist/GetImages/cher?apiKey=XXX
Run Code Online (Sandbox Code Playgroud)
此外,如果您有更复杂的方案,则可以自定义MVC用于查找操作的路由规则.您的global.asax文件包含可自定义的路由规则.默认情况下,规则如下所示:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Run Code Online (Sandbox Code Playgroud)
如果你想支持一个网址
/Artist/GetImages/cher/api-key
Run Code Online (Sandbox Code Playgroud)
你可以添加如下路线:
routes.MapRoute(
"ArtistImages", // Route name
"{controller}/{action}/{artistName}/{apikey}", // URL with parameters
new { controller = "Home", action = "Index", artistName = "", apikey = "" } // Parameter defaults
);
Run Code Online (Sandbox Code Playgroud)
和上面第一个例子的方法一样.
Ber*_*ken 25
从MVC 5开始,您还可以使用"属性路由"将URL参数配置移动到控制器.
有关详细讨论,请访问:http: //blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
摘要:
首先启用属性路由
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用属性来定义参数和可选的数据类型
public class BooksController : Controller
{
// eg: /books
// eg: /books/1430210079
[Route("books/{isbn?}")]
public ActionResult View(string isbn)
Run Code Online (Sandbox Code Playgroud)
Geo*_*ker 21
您可以通过查询字符串传递任意参数,但您也可以设置自定义路由以RESTful方式处理它:
http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
api_key=b25b959554ed76058ac220b7b2e0a026
Run Code Online (Sandbox Code Playgroud)
那可能是:
routes.MapRoute(
"ArtistsImages",
"{ws}/artists/{artist}/{action}/{*apikey}",
new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
);
Run Code Online (Sandbox Code Playgroud)
所以,如果有人使用以下路线:
ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/
Run Code Online (Sandbox Code Playgroud)
它会将它们带到你的示例查询字符串所在的相同位置.
以上只是一个示例,并不适用您必须设置的业务规则和约束,以确保人们不会"破解"URL.
归档时间: |
|
查看次数: |
268560 次 |
最近记录: |