在 ASP.NET Core Web Api 中返回自定义错误消息

Ray*_*Ray 6 asp.net asp.net-web-api asp.net-core

我正在用ASP.NET CORE 1.1. 我想弄清楚如何返回带有不可接受状态代码的错误消息406

这是我在其中一个 Api 控制器中编写的方法:

[HttpPost]
    public async Task<IActionResult> PostStoreCoolerData([FromBody] StoreCoolerData storeCoolerData)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.StoreCoolerData.Add(storeCoolerData);
        var addResponse = await _context.SaveChangesAsync();
        if (addResponse > 0)
        {
            var getItemInfo = _context.StoreCoolerData.Include(c => c.CoolerBrand)
                                                      .Include(c => c.CoolerType)
                                                      .Include(c => c.DrinkType)
                                                      .Where(i => i.Id == storeCoolerData.Id);

            return CreatedAtAction("GetStoreCoolerData", new { getItemInfo });
        }
        return StatusCode(406, "There was a problem saving record in the database. Please try again.");
    } 
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我return StatusCode(406, "There was a problem saving record in the database. Please try again.");在代码的末尾有。当我运行代码并尝试通过自定义错误获取响应时,我没有收到自定义错误消息,而是收到了 Not Acceptable 消息。

不确定这是否是正确的方法。有没有其他方法可以包含不是 200 > 或 < 400 的自定义错误消息?

任何帮助都非常感谢。

更新 1

在此处输入图片说明

谢谢,

射线