ASP.NET 核心 3.1 - PostAsync/PostAsJsonAsync 集成测试中的方法总是 returns 错误请求

ASP.NET Core 3.1 - PostAsync/PostAsJsonAsync method in Integration Test always returns Bad Request

这是我在 AuthController 中的注册方法。

[HttpPost(ApiRoutes.Auth.Register)]
public async Task<IActionResult> Register(UserRegistrationRequest request)
{
    var authResponse = await _authService.RegisterAsync(request.Email, request.Password);

    if (!authResponse.Success)
    {
        return BadRequest(new AuthFailedResponse
        {
            Errors = authResponse.Errors
        });
    }

    return Ok(new AuthSuccessResponse
    {
        Token = authResponse.Token,
        RefreshToken = authResponse.RefreshToken
    });
}

我正在尝试使用 TestClient.PostAsync() 方法调用此方法,不幸的是它总是 returns 错误请求。我已经尝试通过导入 Microsoft.AspNet.WebApi.Client 包来调用 TestClient.PostAsJsonAsync(ApiRoutes.Auth.Register, user) 方法,结果是一样的。

var user = new UserRegistrationRequest
    {
        Email = "user1@testtest.com",
        Password = "P@ssw0rd1!!!!!"
    };

var response = await TestClient.PostAsync(
        ApiRoutes.Auth.Register,
        new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8)
        {
            Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
        });

您缺少操作参数中的 FromBody 属性。当您将 json 数据发送到控制器时,它将成为请求 body 的一部分。您可以告诉控制器如何绑定传入的数据,在您的情况下来自 body。所以你的代码应该是这样的:

public async Task<IActionResult> Register([FromBody]UserRegistrationRequest request)
{
    …
}

您可以在 official documentation 中阅读更多关于绑定的信息。