如何从控制器访问 RESTful URL 上的参数?

How can I access the args on the RESTful URL from a Controller?

我问了一个初步的和有点类似的问题

现在我需要知道如何从控制器 method/action.

中的 RESTful URL 中访问值

我有一个名为 PlatypusController 的控制器,其路由在 WebApiConfig 中设置如下:

config.Routes.MapHttpRoute(
    name: "ReportsApi",
    routeTemplate: "api/{controller}/{unit}/{begindate}/{enddate}",
    defaults: new { enddate = RouteParameter.Optional }
);

PlatypusController.cs 有这个代码:

public void Post()
{
    int i = 2; 
}

"int i = 2"当然是废话;我只是把它放在那里,这样我就可以在方法中放置一个断点来验证它是否已达到。当我 select "POST" 并在 Postman 中输入此 URL 时:

http://localhost:52194/api/Platypus/gramps/201509

(当我调用它时,应用程序在端口 52194 上 运行)

但是为了完成一些有价值的事情,我需要 "gramps" 和 URL 中的“201509”。我怎样才能访问那些?我是否需要像这样将它们添加到 Post 方法中:

public void Post(string unit, string begindate)
{
    DoSomething_Anything(unit, begindate);
}

...或者是否有其他方式获取它们,例如从 HttpRequest 对象或其他方式?

和3.14一样简单;这很管用:

public void Post(string unit, string begindate)
{
    string _unit = unit;
    string _begindate = begindate;
}

_unit 是“gramps”,_begindate 是“201509”,使用 URL:

http://localhost:52194/api/Platypus/gramps/201509

...这正是我所需要的。

尝试在 Post 方法中添加 [FromBody]

public void Post([FromBody] string unit, [FromBody] string begindate)
{
    DoSomething_Anything(unit, begindate);
}

查看详细示例: http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

我个人更喜欢在定义我的路由时明确,这就是为什么我推荐属性路由而不是基于约定的路由。

这样,您就可以明确配置每个控制器和操作的路由。

不要在 WebApiConfig 中以这种方式配置路由,只需确保您已通过调用此行初始化属性路由:

config.MapHttpAttributeRoutes();

在 WebApiConfig 文件中。

那么你可以这样做:

[RoutePrefix("api/platypus")]
public class PlatypusController: ApiController
{
     [Route("{unit}/{begindate}")]
     [HttpPost]
     public void Post(string unit, string begindate)
     {
         int i = 2; 
     }
}

要调用此方法,请向 POST 请求:/api/platypus/gramps/201509