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

标签 asp.net-mvc rest asp.net-web-api

假设我有一个具有以下方法的 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 列表中,它们似乎从未被执行。

最佳答案

如果您想将它作为 URI 本身的一部分传递,您必须考虑在 Global.asax 中定义的默认路由。如果您没有更改它,它会说明 URI 在/Controller/action/id 中分解。

例如,uri 'Home/Index/hello' 在 HomeController 类中转换为 Index("hello)。

因此,在这种情况下,如果您将 DateTime 参数的名称更改为“id”而不是“date”,它应该可以工作。

将参数类型从“DateTime”更改为“DateTime?”也可能更安全。以防止错误。其次,mvc 模式中的所有 Controller 方法都应该返回一个 ActionResult 对象。

祝你好运!

关于asp.net-mvc - ASP.NET WEB API 将 DateTime 作为 URI 的一部分传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11160381/

相关文章:

python - 使用 REST API 获取 Azure 事件中心指标?

c# - Asp.net Web API 返回非描述性错误 500

jquery - 如何使用 jquery 获取带有内联样式的 css

rest - Spring Boot REST token 授权和认证最佳实践

asp.net-mvc - 如何增加Azure网站中的最大工作进程?

Java Spring JSON解析错误: Cannot deserialize instance out of START_ARRAY token

c# - 在 POST 参数中接收空值

asp.net-mvc - 将 SPA 分割为多个组件并使用 AngularJS

asp.net - 如何在 Visual Studio 2010 SP1 中打开 MVC 3 项目?

asp.net-mvc - MVC 5.2.2.0 中使用的 UserManager.CreateAsync 默认哈希