简体   繁体   English

ASP.NET 核心 Web API 必需的属性异常处理

[英]ASP.NET Core Web API Required Property Exception Handling

I am using ASP.NET Core for my new REST API project.我正在为我的新项目 REST API 使用 ASP.NET Core。 I've add an ApiExceptionFilter to get any exception non handle by the system.我添加了一个ApiExceptionFilter来获取系统未处理的任何异常。

But the filter couldn't catch the exception from the [Required] property.但是筛选器无法捕获来自 [Required] 属性的异常。 The request will get 400 response with the message.该请求将获得 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"
}

I want to customize the error message as the ApiExcetionFilter did.我想像ApiExcetionFilter那样自定义错误消息。 I try to implement UseExceptionHandler but didn't get it works.我尝试实施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);
            }));

Do I have to implement other functions or I did something wrong?我必须实现其他功能还是我做错了什么? Thanks谢谢

If I'm understanding what you are trying to do, the error is indicating that this is a bad request (response code being 400), rather than an exception.如果我理解你正在尝试做什么,错误表明这是一个错误的请求(响应代码为 400),而不是异常。 you could create your own custom attribute by extending ValidationAttribute and use it in place of the Required attribute, and throw the exception from within.您可以通过扩展ValidationAttribute并使用它代替Required属性来创建自己的自定义属性,并从内部抛出异常。

Something like this:是这样的:

    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. 该文档应该有助于更复杂的场景。

Any exception thrown from within your custom attribute should then be caught by the exception handler.从您的自定义属性中抛出的任何异常都应该被异常处理程序捕获。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM