asp.net - 如何将 DateTime 值发布到 Web API 2 Controller

标签 asp.net json asp.net-mvc asp.net-web-api fiddler

我有一个示例 Controller :

[RoutePrefix("api/Example")]
public class ExampleController : ApiController
{
    [Route("Foo")]
    [HttpGet]
    public string Foo([FromUri] string startDate)
    {
        return "This is working";
    }

    [Route("Bar")]
    [HttpPost]
    public string Bar([FromBody] DateTime startDate)
    {
        return "This is not working";
    }
}

当我向以下位置发出 GET 请求时:http://localhost:53456/api/Example/Foo?startDate=2016-01-01 它有效。

当我 POST 到 http://localhost:53456/api/Example/Bar 时,我收到 HTTP/1.1 400 Bad Request 错误。

这是我的 POST 数据:

{
"startDate":"2016-01-01T00:00:00.0000000-00:00"
}

我做错了什么?

最佳答案

您不能直接发布非对象,您需要在使用 FromBody 时将它们包装在对象容器中。

[RoutePrefix("api/Example")]
public class ExampleController : ApiController
{
    [Route("Foo")]
    [HttpGet]
    public string Foo([FromUri] string startDate)
    {
        return "This is working";
    }

    [Route("Bar")]
    [HttpPost]
    public string Bar([FromBody] BarData data)
    {
        return "This is not working";
    }
}

public class BarData{
    public DateTime startDate {get;set;}
}

另一种可能的工作方式是,如果您使用 = 符号对值进行表单编码(请注意,您将其作为非对象,花括号已被删除)。

"=2016-01-01T00:00:00.0000000-00:00"

关于asp.net - 如何将 DateTime 值发布到 Web API 2 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004405/

相关文章:

jquery - 背景图像显示在弹出消息上

mysql - 当我尝试使用 MySQL 中的身份存储注册用户时出错

c# - ASP.NET Core 2 没有配置身份验证处理程序来处理方案

c# - F# 网络开发

c# - 如何将异常序列化为 Json

c++ - 如何使用 Qt 处理 json 中编码的西里尔字母数据?

c# - 如何将数据插入到 asp.net 中现有的 xml 文件中?

c# - 我可以使用C#在ASP.NET中创建错误日志吗?

json - NodaTime 间隔 JSON 序列化

jquery - 访问 razor 内的 javascript 变量