我有一个单元测试代码,可以将请求发送到HttpPost方法。
[Test]
public async Task ValidateToken()
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string("test", "test")
};
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var response = await httpClient.PostAsync("/api/token/1", content);
Assert.AreEqual(HttpStatusCode.Accepted, response.StatusCode);
}
[Route("api/token")]
public class MyController : BaseApiController
{
private readonly HttpRequest httpRequest;
public MyController(IHttpContextAccessor httpContextAccessor)
{
httpRequest = httpContextAccessor.HttpContext.Request;
}
[HttpPost("{count}")]
public async Task<IActionResult> Post(int count)
{
if(httpRequest.ContentLength)
return BadRequest();
else
return Accepted();
var success= await store.SaveLogStreamAsync(httpRequest.Body, count);
return success ? Accepted() : InternalServerError();
}
}
此单元测试始终会失败,因为httpRequest.ContentLength
为空。但是,当我在此行上放置一个断点并检查ContentLength
的{{1}}时,它总是大于0。
content
此外,当我在到达Action方法之前放置一个断点时,ContentLength不再为0。我在想,发送内容时会有一些延迟吗?
编辑:
我发现,从单元测试中进行测试时,var response = await httpClient.PostAsync("/api/token/1", content);
的类型为httpRequest.Body
和MemoryStream
从邮递员发送请求时,httpRequest.ContentLength = null
的类型为httpRequest.Body
,FrameRequestStream
始终具有值。
答案 0 :(得分:1)
您可以通过以下方法检查请求:
var length= Request.Content.Headers.ContentLength ;
Dunno httpRequest
变量来自哪里