如何在C#(Xamarin)应用中向.NET API提交DateTime数据?
解决Xamarin向.NET API提交DateTime数据的问题
这个问题我之前也碰到过,核心原因是FormUrlEncodedContent只接受字符串类型的键值对,直接把DateTime转字符串时,默认的本地化格式(比如中文环境的yyyy/MM/dd)和API端的解析逻辑不匹配,导致解析失败后 fallback 到DateTime类型的默认值01/01/1900。下面是几种可靠的解决方案:
方案1:使用ISO 8601标准格式转换DateTime
这是最推荐的方式,因为ISO 8601是跨平台、跨文化的日期时间标准格式,.NET API的模型绑定会自动正确解析它。
修改你的代码,把DateTime转成ISO格式的字符串:
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), // 用"o"格式符生成ISO 8601标准字符串,比如:2023-10-05T14:48:00.0000000Z new KeyValuePair<string, string>("DateOfBirth", u.DateOfBirth.ToString("o")) }); HttpResponseMessage response = await client.PostAsync("/api/Account/Register", formContent);
如果只需要日期部分(不需要时间),可以用ToString("yyyy-MM-dd"),但要确保API端对应的模型属性也只处理日期。
方案2:改用JSON格式提交数据
如果你的API支持JSON接收,这种方式更可靠,能避免所有格式匹配问题,尤其适合复杂模型。
步骤1:定义客户端模型(和API端模型对应)
public class RegisterRequest { public string Email { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } public string Gender { get; set; } public DateTime DateOfBirth { get; set; } }
步骤2:序列化并发送JSON请求
// 构造请求模型 var registerReq = new RegisterRequest { Email = u.Email, Password = u.Password, ConfirmPassword = u.ConfirmPassword, Gender = u.Gender, DateOfBirth = u.DateOfBirth }; // 序列化JSON(可以用Newtonsoft.Json或System.Text.Json) var jsonStr = JsonConvert.SerializeObject(registerReq); var jsonContent = new StringContent(jsonStr, Encoding.UTF8, "application/json"); // 发送请求 HttpResponseMessage response = await client.PostAsync("/api/Account/Register", jsonContent);
步骤3:API端配置接收
确保API的Register方法用[FromBody]接收模型:
[HttpPost("Register")] public IActionResult Register([FromBody] RegisterRequest model) { // 处理注册逻辑 return Ok(); }
为什么你原来的方法不行?
FormUrlEncodedContent的构造函数只接受KeyValuePair<string, string>类型的集合,直接传KeyValuePair<string, DateTime>会编译报错。- 如果你直接用
u.DateOfBirth.ToString(),它会使用当前线程的文化格式生成字符串(比如中文系统是yyyy/MM/dd),而.NET API默认期望ISO 8601格式,解析失败后就会返回DateTime的默认值01/01/1900。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

