【问题标题】:ASP.NET Core Web API Required Property Exception HandlingASP.NET Core Web API 必需的属性异常处理
【发布时间】:2021-10-07 00:07:28
【问题描述】:

我正在为我的新 REST API 项目使用 ASP.NET Core。我添加了一个ApiExceptionFilter 来获取系统无法处理的任何异常。

但过滤器无法从 [Required] 属性中捕获异常。 该请求将得到 400 响应和消息。

{
    "errors": {
        "XXX": [
            "The XXX field is required."
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-fa92d07cf6c8694c87febb276786aada-6f9327722d0cb84b-00"
}

我想像ApiExcetionFilter 那样自定义错误消息。 我尝试实现UseExceptionHandler,但没有成功。

app.UseExceptionHandler(c => c.Run(async context =>
            {
                var exception = context.Features
                    .Get<Exception>();

                var response = new { error = exception.Message };
                await context.Response.WriteAsJsonAsync(response);
            }));

我必须实现其他功能还是我做错了什么? 谢谢

【问题讨论】:

    标签: c# exception .net-core


    【解决方案1】:

    如果我理解您要执行的操作,则错误表明这是一个错误请求(响应代码为 400),而不是异常。您可以通过扩展 ValidationAttribute 创建自己的自定义属性,并使用它代替 Required 属性,并从内部抛出异常。

    类似这样的:

        using System;
        using System.ComponentModel.DataAnnotations;
    
        [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
        public class RequiredThrowsException : ValidationAttribute
        {
            public RequiredThrowsException(string ErrorMessage = "Some error message here"): base(ErrorMessage) { }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                var val = (string)(value);
                if (val is null || string.IsNullOrEmpty(val))
                    throw new ArgumentNullException(ErrorMessage);
                return ValidationResult.Success;
            }
    

    This documentation should help with more complex scenarios.

    从您的自定义属性中抛出的任何异常都应该被异常处理程序捕获。

    【讨论】:

      猜你喜欢
      • 2016-12-02
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2012-05-04
      • 2019-10-27
      • 1970-01-01
      • 2014-06-12
      相关资源
      最近更新 更多