简体   繁体   English

创建定制模型验证属性

[英]Creating custom model validation attribute

I'm trying to emulate the behavior of the [ApiController] attribute for model validation, however I'd like to return a JSON object I've made with the validation errors in an Error array within the JSON. 我正在尝试模拟[ApiController]属性的行为以进行模型验证,但是我想在JSON中的Error数组中返回使用验证错误制作的JSON对象。

The challenge I'm facing is that I'm unsure how to access validation errors from within the Attribute and I'd like to use the attribute at the class level, so it will run on all controller methods without need of supplying the attribute for each action. 我面临的挑战是我不确定如何从Attribute中访问验证错误,并且我想在类级别使用该属性,因此它可以在所有控制器方法上运行,而无需为其提供属性每个动作。

Any direction would be much appreciated. 任何方向将不胜感激。

edit: linked duplicate is how to create custom attribute. 编辑:链接重复项是如何创建自定义属性。 I'm looking how to access model validation errors from within an attribute. 我正在寻找如何从属性中访问模型验证错误。

I was able to figure out my issue. 我能够弄清楚我的问题。 I was able to utilize ModelState.IsValid in an OnActionExecuting method to access the errors. 我能够在OnActionExecuting方法中利用ModelState.IsValid来访问错误。 Unfortunately I'm not familiar enough with making a class level attribute so I have to apply this to all post/patch methods in order for it to work. 不幸的是,我对制作类级别的属性还不够熟悉,因此我必须将其应用于所有post / patch方法,以使其起作用。 If someone else comes up with a way to do that easily, let me know! 如果有人想出一种轻松做到这一点的方法,请告诉我!

Project.Structure is for formatting JSON for those curious. Project.Structure用于为那些好奇的人格式化JSON。

using System;
using System.Collections.Generic;
using System.Linq;
using Project.Structure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Project.Attributes
{
   public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errorList = new List<string>();
                foreach (var modelError in context.ModelState.Values)
                {
                    errorList.AddRange(modelError.Errors.Select(error => error.ErrorMessage));
                }

                var response = new ResponseDto<object>
                {
                    Success = false,
                    TransactionId = Guid.NewGuid().ToString(),
                    ResponseType = ResponseType.Operation.Description(),
                    Response = null,
                    Errors = errorList,
                    Warnings = null
                };

                context.Result = new BadRequestObjectResult(response);
            }
        }
    }
}

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

相关问题 具有自定义验证属性的模型验证 - Model validation with custom validation attribute 三层深度模型的自定义验证属性 - Custom Validation Attribute for three levels deep model 在自定义验证属性中引用MVC实体模型 - reference an MVC entity model in a custom validation attribute model C# 的自定义验证属性 - Custom Validation Attribute for model C# ASP.NET MVC5创建自定义验证属性不起作用 - ASP.NET MVC5 creating custom validation attribute is not working 如何使用由 model 属性组成的参数创建自定义验证属性 - How to create a custom validation attribute with parameters consisting of model properties 是否有模型验证属性可以在不使用自定义代码的情况下检查参数类型? - Is there an model validation attribute to check parameter types without using custom code? 用于检查我的模型属性中的重复项的自定义验证属性未触发 - Custom validation attribute to check for duplicates among my model properties is not firing 自定义验证属性未在 Model 上验证 - WebAPI C# 和 JSON - Custom Validation Attribute not validating on Model - WebAPI C# and JSON 模型属性验证问题 - Model attribute validation issue
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM