代码之家  ›  专栏  ›  技术社区  ›  Yasser Shaikh

.NET core web api向客户端发送错误请求

  •  -3
  • Yasser Shaikh  · 技术社区  · 8 年前

    // POST: api/Companies
    [HttpPost]
    public void Post([FromBody]string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            // inform the client that request is incorrect.
        }
    }
    

    我想能够告诉客户,这是一个坏的要求,我发现了许多文章,但都是1-2岁,我相信有很多变化,从那时起。所以想知道这个问题的最佳解决方案。

    2 回复  |  直到 8 年前
        1
  •  3
  •   Marcus Höglund    8 年前

    在ControllerBase类中声明的BadRequest方法将创建400响应消息。它已经存在了很多年(新版本,几乎相同的实现),而且它是可靠的,所以使用它

    [HttpPost]
    public IActionResult Post([FromBody]string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return BadRequest("request is incorrect");
        }
    }
    
        2
  •  0
  •   Afzaal Ahmad Zeeshan    8 年前

    建议将方法签名更改为:

    [HttpPost]
    public IHttpActionResult Post([FromBody]string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return BadRequest("Value must be passed in the request body.");
        }
        else
        {
            return Ok("Request was correct");
        }
    }
    

    Ok(...) method ,和 BadRequest("reason") ,以及其他内置类型,如 the HttpActionResult documentation page

    推荐文章