如何访问Web API中的URL参数? [英] How do I access URL parameters in web API?

查看:71
本文介绍了如何访问Web API中的URL参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用.NET Web API创建REST服务.我尝试映射的URL是

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";
}

一切都正确映射,但是如何从GetChapters函数中访问URL中的< video_id> 参数?

Everything maps correctly, but how do I get access to the <video_id> parameter in the URL from within the GetChapters function?

作为一个具体示例,URL如下所示:

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?

推荐答案

只需将 id 参数添加到您的Web服务方法中-ASP.NET Web API将自动将其隐藏到查询字符串参数中或在路由中定义的 {id} 参数:

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";
}

您还可以省略 [HttpGet] [ActionName] 属性,因为在Web API中,名称以"Get"开头的操作方法将被映射到GET请求(将发布"到POST等),并将方法名称的其他部分(章节")视为操作名称.

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.

这篇关于如何访问Web API中的URL参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆