ControllerBase
包含返回 ConflictResult
对象(表示 HTTP 409 响应)的 Conflict()
等方法,该对象派生自 状态代码结果
。生成的响应正文具有内容类型 application/problem+json
并且如下所示:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.8",
"title": "Conflict",
"status": 409,
"traceId": "0HLO99QHFC9QI:00000001"
}
HTTP 410 响应没有内置方法/类,所以我做了一个:
[DefaultStatusCode(410)]
public class GoneResult : StatusCodeResult
{
public GoneResult() : base(410)
{}
}
...
public static class ControllerBaseExtensions
{
public static GoneResult Gone(this ControllerBase controllerBase) // this doesn't give all the problem+JSON attributes
{
return new GoneResult();
}
}
然而,这给出了
{
"type": "about:blank",
"status": 410
}
即 type
值不同,title
和 traceId
字段缺失。
我还想为 HTTP 500 响应创建一个自定义类,其中包含带有错误消息的 message
字段。我试过返回 StatusCode(StatusCodes.Status500InternalServerError)
,它给我的最小 application/problem+json
响应与我的 Gone()
相同方法;我也试过返回 StatusCode(StatusCodes.Status500InternalServerError, message)
,这给了我错误消息,但将响应格式化为 text/plain
。
最佳答案
生成 ProblemDetails
响应的代码不知道 410
状态代码,因此它没有关联的 Link
和 Title
属性以在构建响应对象时使用。要添加此意识,请配置 ApiBehaviorOptions
在 ConfigureServices
中,像这样:
services.Configure<ApiBehaviorOptions>(options =>
{
options.ClientErrorMapping[410] = new ClientErrorData
{
Title = "Gone",
Link = "https://tools.ietf.org/html/rfc7231#section-6.5.9"
};
});
ClientErrorMapping
是 int
(状态代码)到 ClientErrorData
的字典.请注意,我在上面用于 Link
的值确实指向 RFC 的正确部分。
关于c# - .NET 核心 Web API : return a custom HTTP status code with Content Type application/problem+json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57045212/