【问题标题】:Client.PostAsync (with Json) Gets 400 Bad RequestClient.PostAsync(使用 Json)获取 400 错误请求
【发布时间】:2019-01-01 00:32:40
【问题描述】:

我正在尝试为我的 .Net Core Web Api 创建集成测试

但我总是收到 400 Bad Request 响应。我在下面分享详细信息

这是我的控制器方法

public IActionResult UpdateProductById([FromBody]int id, string description)
{
    var result = ProductService.UpdateProductById(id, description);
    if (result.Exception == null)
        return Ok(result);
    else
        return BadRequest(result.Exception.Message);
}

这是我的测试类(试图发布)

[Fact]
public async Task UpdateProductById_Test_WithProduct()
{
    var product = new
    {
        id = 1,
        description = "foo"
    };

    var productObj= JsonConvert.SerializeObject(product);

    var buffer = System.Text.Encoding.UTF8.GetBytes(productObj);
    var byteContent = new ByteArrayContent(buffer);

    byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var result = await _tester.Client.PostAsync("/api/1.0/UpdateProductById", byteContent);

    result.StatusCode.Should().Be(HttpStatusCode.OK);
}

【问题讨论】:

  • 您好,异常消息中的内容是什么?
  • 您在调用“BadRequest”时隐藏了真正的错误。
  • Nkosi 的评论解决了 PoulBak 和 Stefan 的问题。非常感谢您的关注

标签: c# asp.net-core


【解决方案1】:

测试发送请求正文中的所有内容,但操作仅绑定id。很可能描述为空,并导致更新出现问题。

创建一个模型来保存数据

public class ProductModel {
    public int id { get; set; } 
    public string description { get; set; }
}

重构操作以从请求正文中获取内容

[HttpPost]
public IActionResult UpdateProductById([FromBody]ProductModel model) {
    if(ModelState.IsValid) {
        var result = ProductService.UpdateProductById(model.id, model.description);
        if (result.Exception == null)
            return Ok(result);
        else
            return BadRequest(result.Exception.Message);
    }
    return BadRequest(ModelState);
}

【讨论】:

    猜你喜欢
    • 2017-11-27
    • 2013-06-30
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2015-10-15
    相关资源
    最近更新 更多