asp.net-core - 如何使用 .NET Core 自定义 Web API 中的错误响应?

标签 asp.net-core model asp.net-core-webapi

我正在使用 .NET Core 2.2 和 Web API。我创建了一个类,即,如下所示:

public class NotificationRequestModel
{
    [Required]
    public string DeviceId { get; set; }
    [Required]
    public string FirebaseToken { get; set; }
    [Required]
    public string OS { get; set; }

    public int StoreId { get; set; }
}
使用上面的类,我创建了一种方法。现在我想返回一个自定义对象,但它返回的是它自己的对象。
API方法是:
public ActionResult<bool> UpdateFirebaseToken(NotificationRequestModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(FormatOutput(ModelState.Values));
    }
    var result = _notificationService.InsertOrUpdateFirebaseToken(model);
    return Ok(result);
}
这里FormatOutput方法是格式化输出。
protected Base FormatOutput(object input, int code = 0, string message = "", string[] details = null)
{
    Base baseResult = new Base();
    baseResult.Status = code;
    baseResult.Error = message;
    baseResult.TimeStamp = CommonHelper.CurrentTimeStamp;
    baseResult.Code = code;
    baseResult.Details = details;
    baseResult.Message = message; //Enum.Parse<APIResponseMessageEnum>(code.ToString(), true); // (enum of code get value from language)
    return baseResult;
}
但问题是它返回:
{
  "errors": {
    "DeviceId": [
      "The DeviceId field is required."
    ]
  },
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "80000049-0001-fc00-b63f-84710c7967bb"
}
我想用我的模型自定义这个错误。我需要来自返回输出的错误消息和详细信息并将其传递给我的模型。我该怎么做?我曾尝试调试我的代码,发现 API 方法上的断点没有调用。所以我无法处理我的自定义方法。有什么解决办法吗?我做错了什么?

最佳答案

正如克里斯分析的那样,您的问题是由 Automatic HTTP 400 responses 引起的。 .
对于快速解决方案,您可以通过以下方式抑制此功能

services.AddMvc()
        .ConfigureApiBehaviorOptions(options => {
            options.SuppressModelStateInvalidFilter = true;
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
对于一种有效的方法,您可以遵循 Chris 的建议,如下所示:
services.AddMvc()
        .ConfigureApiBehaviorOptions(options => {
            //options.SuppressModelStateInvalidFilter = true;
            options.InvalidModelStateResponseFactory = actionContext =>
            {
                var modelState = actionContext.ModelState.Values;
                return new BadRequestObjectResult(FormatOutput(modelState));
            };
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
而且,您不再需要在您的操作中定义下面的代码。
if (!ModelState.IsValid)
{
    return BadRequest(FormatOutput(ModelState.Values));
}

关于asp.net-core - 如何使用 .NET Core 自定义 Web API 中的错误响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54942192/

相关文章:

.net - 使用Helm安装时如何配置nginx?

asp.net-core - 从 ASP.NET Core 2.1 应用程序中删除 "Server" header

javascript - 风 sails 多型号关联

python - 客户与公司的关系

asp.net-core - 如何禁用所有 API Controller 的状态代码页中间件?

c# - 带有 .Net Core SDK 3.0 预览版的 Visual Studio Code 和 Omnisharp Extension 错误

ruby-on-rails - ruby 和 Rails : Metaprogramming variables to become class methods

c# - 我如何解决 Cannot create a DbSet for 'CUserMasterLocal' because this type is not included in the model for the context

asp.net-core - 如何为 ResponseCacheAttribute 动态设置持续时间

c# - 如何在 ASP.NET Core Web API 中传递一个 int 数组