在 ASP.NET Core 3.1 中向 HTTP 400 错误请求添加消息

Ioa*_* B. 5 httprequest bad-request asp.net-core asp.net-core-webapi asp.net-core-3.1

有没有办法可以将消息添加到BadRequest操作结果中,并使该消息对外部客户端(例如 Postman)可见?我正在使用 ASP.NET Core 3.1。

\n\n

我的部分代码包含在下面。我想说的是问题是什么\xe2\x80\x94e.g.,id正文中发送的内容与从 URL 中获取的内容不同。现在,我正在使用Error我制作的一个对象,其中包含错误代码和消息。但当我发送请求时,这些在邮递员中不可见。

\n\n
public ActionResult PutColour(int id, Colour colour)\n{\n    if (id != colour.Id)\n    {\n        return BadRequest(new Error("IDNotTheSame","ID from URL is not the same as in the body."));\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Chr*_*att 9

您传递给的内容BadRequest将被序列化并作为响应正文返回。如果没有任何结果,唯一的解释是您没有任何Error可以序列化的公共属性。例如,如果您有类似的内容:

public class Error
{
    public Error(string type, string description)
    {
        Type = type;
        Description = description;
    }

    public string Type { get; private set }
    public string Description { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,您会得到如下响应:

{
    "type": "IDNotTheSame",
    "description": "ID from URL is not the same as in the body."
}
Run Code Online (Sandbox Code Playgroud)

不确定你的Error班级目前在做什么。然而,这可能是不必要的,因为你可以使用ModelState

ModelState.AddModelError("Id", "ID from URL is not the same as in the body.");
return BadRequest(ModelState);
Run Code Online (Sandbox Code Playgroud)

最后,也许应该说,这首先是毫无意义的验证。您根本不应该使用模型发送 id(始终使用视图模型,而不是实体类),即使您确实发送了它,您也可以简单地用 URL 中的值覆盖它:

model.Id = id;
Run Code Online (Sandbox Code Playgroud)

完毕。没有问题,您无需担心发回错误。