问题
I am trying to create a REST service using the .NET Web API. The URL I am trying to map is
/api/<controller>/<videoId>/chapters
I have a route setup that looks like the following:
RouteTable.Routes.MapHttpRoute(name: "Route1",
routeTemplate: "api/video/{id}/{action}",
defaults: new { controller = "Video", action = "Chapters"});
Which maps the following function in the controller:
[HttpGet]
[ActionName("Chapters")]
public string GetChapters() {
return "get chapters";
}
Everything maps correctly, but how do I get access to the <video_id>
parameter in the URL from within the GetChapters function?
As a concrete example, the URL looks like this:
http://localhost/api/video/1/chapters
How do I get access to the parameters after controller, in this 1?
回答1:
Just add id
parameter to your web service method - it will be automatically blinded by ASP.NET Web API to the query string parameter or {id}
parameter defined in the route:
public string GetChapters(int id) {
return "get chapters by video id";
}
Also you can omit [HttpGet]
and [ActionName]
attributes, because in Web API action methods with name starting from 'Get' will be mapped to GET requests ('Post' to POST and so on), and other part of the method name ('Chapters') is treated as the action name.
来源:https://stackoverflow.com/questions/14009700/how-do-i-access-url-parameters-in-web-api