Dotnet
WebAPI错误默认输出
Controller有时候会默认触发一些错误,例如model中配置了Required,没传值会触发错误,且不会进入Action,如果想接管这个错误,可使用配置全局来实现,如下所示
services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var errorMessage = context.ModelState.Values.FirstOrDefault()?.Errors.FirstOrDefault()?.ErrorMessage;
return new Microsoft.AspNetCore.Mvc.JsonResult(APIResult.CreateError(0, errorMessage));
};
})