假设我有一个具有以下方法的 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/