How do I access URL parameters in web API?

柔情痞子 提交于 2021-02-20 04:14:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!