【问题标题】:Send DateTime in Post Request在 Post 请求中发送 DateTime
【发布时间】:2018-05-19 17:28:57
【问题描述】:

您好,我有 C# (Xamarin) 应用程序和 .net API。如何将 DateTime 发布到我的 .Net API?

.Net API

目前我有:

        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("Email", u.Email),
            new KeyValuePair<string, string>("Password", u.Password),
            new KeyValuePair<string, string>("ConfirmPassword", u.ConfirmPassword),
            new KeyValuePair<string, string>("Gender", u.Gender),
            new KeyValuePair<string, string>("DateOfBirth", u.DateOfBirth)
        });


        HttpResponseMessage response = await client.PostAsync("/api/Account/Register", formContent);

所有字符串都可以正常工作,但是我无法弄清楚 DateTime 字符串。我猜它是:

       KeyValuePair<string, DateTime>("DateOfBirth", u.DateOfBirth)

但这不起作用。如果我将 DateTime 转换为字符串,则服务器上的日期只是 01/01/1900,这也不正确。

【问题讨论】:

    标签: c# datetime asp.net-web-api dotnet-httpclient


    【解决方案1】:

    发送刻度怎么样?

    DataTime 转换为刻度并发送:

    var ticks = DateTime.UtcNow.Ticks;
    

    【讨论】:

    • 另外,使用 DateTime.UtcNow 而不是仅仅使用 ".Now" 可能是值得的,因为您永远无法确定服务器和客户端在地理上或配置上处于同一时区。
    • @YurySchkatula 对了,我其实只是随便选了一个DataTime(也就是Now)来展示Ticks属性的用法。但以富有成效的方式,确保UtcNow 是可靠的方式。
    • 我喜欢这个解决方案。它让一切变得非常简单。
    【解决方案2】:

    我实际上最终序列化了具有我想要发布的所有属性的对象,这似乎有效。

    string postBody = JsonConvert.SerializeObject(u);
    
    HttpResponseMessage response = await client.PostAsync("/api/Account/Register", new StringContent(postBody, Encoding.UTF8, "application/json")); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 2011-03-20
      • 1970-01-01
      • 2019-01-13
      相关资源
      最近更新 更多