有一个WebApi 是 HttpPatch 的源码如下:
[HttpPatch]
[Route("test/{testId}")]
public async Task<IActionResult> UpdateA([FromBody]TestItem test, int testId)
{
//.....
}
[Fact]
public async Task UpdateATest()
{
var requestMessage = new HttpRequestMessage(new HttpMethod("PATCH"), $"test/{testId}")
{
Content = new ObjectContent<dynamic>(new
{
UserID = 1,
Title = "Second Queston From Web Api",
Content = "Second Question from Web Api"
}, "application/json")
};
var response = await _httpClient.SendAsync(requestMessage);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
在.NET-Core
上 ObjectContent
是不支持的,请问,我需要如何进行测试 HttpPatch
的请求呢?
1、可以使用StringContent替代
var requestMessage = new HttpRequestMessage(new HttpMethod("PATCH"), $"questions/{Qid}")
{
Content = new StringContent(JsonConvert.SerializeObject(new
{
UserID = 2,
Title = "Second Queston From Web Api",
Content = "Second Question from Web Api"
}),Encoding.UTF8,"Application/json")
};
var response = await _httpClient.SendAsync(requestMessage);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
StringContent
和 ObjectContent
的比较:
http://stackoverflow.com/questions/30704584/stringcontent-vs-objectcontent