示例#1
0
 /// <summary>
 /// Note: This needs to be called after 'services.AddControllers()'
 /// </summary>
 public static void AddCustomExceptionHandler(this IServiceCollection services)
 {
     services.Configure <ApiBehaviorOptions>(options =>
     {
         options.InvalidModelStateResponseFactory = actionContext =>
         {
             // Ensure that model validation errors return the same type of messages as the middleware
             var details = new ApiModelValidationException(actionContext.ModelState);
             return(new BadRequestObjectResult(details.ToString(true)));
         };
     });
 }
        private void HandleValidationException(ExceptionContext context)
        {
            ApiModelValidationException exception = context.Exception as ApiModelValidationException;

            ValidationProblemDetails details = new ValidationProblemDetails(exception.Errors)
            {
                Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
            };

            context.Result = new BadRequestObjectResult(details);

            context.ExceptionHandled = true;
        }
示例#3
0
        private void HandleValidationException(ExceptionContext context)
        {
            // MS reference: https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0#automatic-http-400-responses
            ApiModelValidationException exception = context.Exception as ApiModelValidationException;

            ValidationProblemDetails details = new ValidationProblemDetails(exception.Errors)
            {
                Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
            };

            context.Result = new BadRequestObjectResult(details);

            context.ExceptionHandled = true;
        }