chi*_*fet 5 rest asp.net-mvc asp.net-web-api
说我有一个使用以下方法的控制器:
public int Get(DateTime date)
{
// return count from a repository based on the date
}
Run Code Online (Sandbox Code Playgroud)
我希望能够在将日期作为URI本身的一部分传递时访问方法,但是目前,我只能在将日期作为查询字符串传递时使其工作。例如:
Get/2012-06-21T16%3A49%3A54-05%3A00 // does not work
Get?date=2005-11-13%205%3A30%3A00 // works
Run Code Online (Sandbox Code Playgroud)
有什么想法可以使它起作用吗?我尝试使用自定义MediaTypeFormatters,但是即使将它们添加到HttpConfiguration的Formatters列表中,它们也似乎从未执行过。
让我们看一下默认的 MVC 路由代码:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", **id** = UrlParameter.Optional}
);
Run Code Online (Sandbox Code Playgroud)
好的。看到名字了吗?您需要将方法参数命名为“id”,以便模型绑定器知道您想要绑定到它。
用这个 -
public int Get(DateTime id)// Whatever id value I get try to serialize it to datetime type.
{ //If I couldn't specify a normalized NET datetime object, then set id param to null.
// return count from a repository based on the date
}
Run Code Online (Sandbox Code Playgroud)