Ed *_*ham 5 c# asp.net-core asp.net-core-webapi
ControllerBaseConflict()包含诸如返回ConflictResult派生自 的对象(表示 HTTP 409 响应)之类的方法StatusCodeResult。生成的响应正文具有内容类型application/problem+json,如下所示:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.8",
"title": "Conflict",
"status": 409,
"traceId": "0HLO99QHFC9QI:00000001"
}
Run Code Online (Sandbox Code Playgroud)
没有用于 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();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,这给出了
{
"type": "about:blank",
"status": 410
}
Run Code Online (Sandbox Code Playgroud)
即,type值不同并且缺少title和字段。traceId
我还想为 HTTP 500 响应创建一个自定义类,其中包含message带有错误消息的字段。我尝试过 return ,这给了我与我的方法StatusCode(StatusCodes.Status500InternalServerError)相同的最小响应;我也尝试过 return ,这给了我错误消息,但将响应格式设置为.application/problem+jsonGone()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"
};
});
Run Code Online (Sandbox Code Playgroud)
ClientErrorMappingint是(状态代码) 到的字典ClientErrorData。请注意,我在上面使用的值Link确实指向 RFC 的正确部分。
| 归档时间: |
|
| 查看次数: |
6319 次 |
| 最近记录: |