asp.net-mvc – ASP.NET WEB API将DateTime作为URI的一部分传递给Controller

假设我有一个使用以下方法的Controller:

public int Get(DateTime date)
{
    // return count from a repository based on the date
}

我希望能够在将日期作为URI本身的一部分传递时访问方法,但是目前我只能在将日期作为查询字符串传递时才能使用它.例如:

Get/2012-06-21T16%3A49%3A54-05%3A00 // does not work
Get?date=2005-11-13%205%3A30%3A00 // works

任何想法我怎么能让这个工作?我已尝试使用自定义MediaTypeFormatters,但即使我将它们添加到HttpConfiguration的Formatters列表中,它们似乎也从未被执行过.

解决方法

让我们看看你的认MVC路由代码

routes.MapRoute(
            "Default","{controller}/{action}/{id}",new {controller = "Home",action = "Index",**id** = UrlParameter.Optional}
            );

好的.看到名称ID?您需要将方法参数命名为“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
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....