我正在使用ASP.NET Core 2.2 ApiController,并且具有以下内容:
[ApiController]
public class PostController : Controller {
[HttpGet("posts")]
public async Task<IActionResult> Get() {
return BadRequest();
}
}
在这种情况下,我得到以下响应:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "0HLMFSL0C7SKB:00000001"
}
但是如果我返回如下数据:
[ApiController]
public class PostController : Controller {
[HttpGet("posts")]
public async Task<IActionResult> Get() {
List<String> errors = new List<String> { "Code is invalid" };
return BadRequest(new { errors = errors });
}
}
我得到以下信息:
{
"errors": ["Code is invalid"]
}
为什么没有内容返回时ApiController会添加类型,标题,状态和traceId?
我希望响应始终像这样:
{
"errors": ["Code is invalid"],
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "0HLMFSL0C7SKB:00000001"
}
答案 0 :(得分:1)
默认ControllerBase.BadRequest()
响应内容是因为您已将[ApiController]
属性应用于控制器。在线记录如下:
当兼容版本为2.2或更高版本时,MVC会将错误结果(状态码为400或更高的结果)转换为
ProblemDetails
的结果。ProblemDetails
类型基于RFC 7807规范,用于在HTTP响应中提供机器可读的错误详细信息。
这包括type
,title,
状态and
traceId`值:https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#problem-details-for-error-status-codes
如果您未应用[ApiController]
,则ControllerBase.BadRequest()
将返回带有HTTP 400
状态码的空响应。
接受ControllerBase.BadRequest
或value
响应对象的model
的所有重载都将被序列化并返回,而不是使用ApiController
默认响应。
答案 1 :(得分:1)
对于ProblemDetails
,取决于ObjectResult
是否继承自IClientErrorActionResult
。
您可以按照以下步骤进行解决:
MyBadRequestObjectResult
public class MyBadRequestObjectResult : BadRequestObjectResult, IClientErrorActionResult
{
public MyBadRequestObjectResult() : base((object)null)
{
}
public MyBadRequestObjectResult(object error) : base(error)
{
}
}
自定义ProblemDetailsErrorFactory
public class ProblemDetailsErrorFactory: IClientErrorFactory
{
private static readonly string TraceIdentifierKey = "traceId";
private static readonly string ErrorsKey = "errors";
private readonly ApiBehaviorOptions _options;
public ProblemDetailsErrorFactory(IOptions<ApiBehaviorOptions> options)
{
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
}
public IActionResult GetClientError(ActionContext actionContext, IClientErrorActionResult clientError)
{
var problemDetails = new ProblemDetails
{
Status = clientError.StatusCode,
Type = "about:blank",
};
if (clientError.StatusCode is int statusCode &&
_options.ClientErrorMapping.TryGetValue(statusCode, out var errorData))
{
problemDetails.Title = errorData.Title;
problemDetails.Type = errorData.Link;
SetErrors(actionContext, problemDetails);
SetTraceId(actionContext, problemDetails);
}
return new ObjectResult(problemDetails)
{
StatusCode = problemDetails.Status,
ContentTypes =
{
"application/problem+json",
"application/problem+xml",
},
};
}
internal static void SetErrors(ActionContext actionContext, ProblemDetails problemDetails)
{
if (actionContext is ResultExecutingContext resultExecutingContext)
{
if (resultExecutingContext.Result is BadRequestObjectResult result)
{
problemDetails.Extensions[ErrorsKey] = result.Value;
}
}
//var errors = actionContext.HttpContext.
}
internal static void SetTraceId(ActionContext actionContext, ProblemDetails problemDetails)
{
var traceId = Activity.Current?.Id ?? actionContext.HttpContext.TraceIdentifier;
problemDetails.Extensions[TraceIdentifierKey] = traceId;
}
}
注册ProblemDetailsErrorFactory
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IClientErrorFactory, ProblemDetailsErrorFactory>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
控制器操作
[ApiController]
public class PostController : Controller
{
[HttpGet("posts")]
public IActionResult Get()
{
return new MyBadRequestObjectResult();
}
[HttpGet("posts1")]
public IActionResult Get1()
{
List<String> errors = new List<String> { "Code is invalid" };
return new MyBadRequestObjectResult(errors);
}
}
答案 2 :(得分:0)
尝试使用JsonConvert序列化您的错误请求。
返回BadRequest(JsonConvert.Serialize(新列表{“代码无效”}));
答案 3 :(得分:0)
您无需返回BadRequest()
结果,而只需返回ValidationProblem()
结果。这将为您提供ProblemDetails对象响应,并填充当前的ModelState错误。