Asp.net Core 的 POST 方法将 DateTime.Now 转换为模型绑定的最小日期
Asp.net Core's POST method converting DateTime.Now to Min Date on model binding
我有一个简单的集成测试。
[TestMethod]
public async Task INT_GetSomething_Sucess()
{
//Arrange
HttpResponseMessage response;
BidMonthDetails returnedObj;
//Act
try
{
string request = JsonConvert.SerializeObject(DateTime.Now);
response = await TestClient.PostAsync("/api/Trade/GetSomething", new StringContent(request, Encoding.UTF8, "application/json"));
var jsonString = await response.Content.ReadAsStringAsync();
returnedObj = JsonConvert.DeserializeObject<MyModel>(jsonString);
}
catch (Exception ex)
{
throw ex;
}
//Assert
Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK);
Assert.IsNotNull(returnedObj);
}
这将测试 Trade 控制器中名为 GetSomething 的函数
[HttpPost]
public async Task<ActionResult<MyModel>> GetSomething(DateTime date)
{
此时 "date" 只是最小日期。我期待今天的约会。
默认情况下 DateTime
参数假定来自查询字符串。由于您没有 date
查询字符串参数,它默认为 DateTime
的默认值,即 DateTime.Min
要解决这个问题,您有两种选择:
1)用FromBody属性修饰参数:
public async Task<ActionResult<MyModel>> GetSomething([FromBody]DateTime date)
2) 将值放在查询字符串而不是正文中:
response = await TestClient.PostAsync($"/api/Trade/GetSomething?date={DateTime.UtcNow}"...
我有一个简单的集成测试。
[TestMethod]
public async Task INT_GetSomething_Sucess()
{
//Arrange
HttpResponseMessage response;
BidMonthDetails returnedObj;
//Act
try
{
string request = JsonConvert.SerializeObject(DateTime.Now);
response = await TestClient.PostAsync("/api/Trade/GetSomething", new StringContent(request, Encoding.UTF8, "application/json"));
var jsonString = await response.Content.ReadAsStringAsync();
returnedObj = JsonConvert.DeserializeObject<MyModel>(jsonString);
}
catch (Exception ex)
{
throw ex;
}
//Assert
Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK);
Assert.IsNotNull(returnedObj);
}
这将测试 Trade 控制器中名为 GetSomething 的函数
[HttpPost]
public async Task<ActionResult<MyModel>> GetSomething(DateTime date)
{
此时 "date" 只是最小日期。我期待今天的约会。
默认情况下 DateTime
参数假定来自查询字符串。由于您没有 date
查询字符串参数,它默认为 DateTime
的默认值,即 DateTime.Min
要解决这个问题,您有两种选择:
1)用FromBody属性修饰参数:
public async Task<ActionResult<MyModel>> GetSomething([FromBody]DateTime date)
2) 将值放在查询字符串而不是正文中:
response = await TestClient.PostAsync($"/api/Trade/GetSomething?date={DateTime.UtcNow}"...