C# 如何从ModelState获取验证规则

C# 如何从ModelState获取验证规则,c#,asp.net-core,data-annotations,asp.net-core-3.1,modelstate,C#,Asp.net Core,Data Annotations,Asp.net Core 3.1,Modelstate,是否仍然可以从ModelState字典中获取验证规则。 比如说 我的模型中有以下数据注释属性 [StringLength(64, MinimumLength = 8, ErrorMessage = "{0} must be between {2} to {1} characters")] public string Password { get; set; } 因此,在验证Modelstate时,我们可以得到MinimumLength和maxiumlength 我想发送这两个值作为响应,以便前

是否仍然可以从ModelState字典中获取验证规则。 比如说

我的模型中有以下数据注释属性

[StringLength(64, MinimumLength = 8, ErrorMessage = "{0} must be between {2} to {1} characters")]
public string Password { get; set; }
因此,在验证
Modelstate
时,我们可以得到
MinimumLength
maxiumlength

我想发送这两个值作为响应,以便前端可以使用这些值生成本地化消息

我的答复如下

{
“错误代码”:1234,
“消息”:“密码必须介于8到64个字符之间”,
“args”:[“8”,“64”]
}
因此,使用此错误代码前端可以使用
args
生成本地化消息

因此,在验证Modelstate时,我们可以得到最小长度和 最大长度

可以使用从模型类型获取属性值

var type=ViewModel.GetType()
var properties=type.GetProperties();
foreach(属性中的var属性)
{
var attributes=property.GetCustomAttributes(true);
foreach(属性中的对象属性)
{
var stringLengthAttribute=属性为stringLengthAttribute;
if(StringLengthatAttribute==null)
{
继续;
}
var maximumLength=stringLengthAttribute.maximumLength;
var minimumLength=stringLengthAttribute.minimumLength;
}
}

即使我们添加
配置APIbehaviorOptions
对象不包含验证规则,也很难做到这一点 我建议最简单的方法是在字符串中创建一个json对象,这样您就可以直接使用所需的格式

 [StringLength(64, MinimumLength = 8, ErrorMessage = "{{error:'{0} must be between {2} to {1} characters ',args:'[{1},{2}]' }}") ]

正如@Józef Podlecki所说,您可以使用
反射
来实现您的需求

你也可以参考

以下是实现此目标的一般方法:

  public class PerInfo
    {
        [StringLength(64, MinimumLength = 8, ErrorMessage = "{0} must be between {2} to {1} characters")]
        public string Password { get; set; }
    }
按照您提供的响应格式,您可以创建错误模型:

 public class CusError
    {
        public long errorCode { get; set; }
        public string message { get; set; }
        public string[] args { get; set; }
    }
代码:

[HttpPost]
公共IActionResult验证(PerInfo PerInfo)
{
如果(!ModelState.IsValid)
{
var error=GenerateValidationModel();
返回请求(错误);
}
返回Ok();
}
私有CusError GenerateValidationModel()
{
var error=new CusError();
foreach(typeof(T).GetProperties()中的var prop)
{
object[]attrs=prop.GetCustomAttributes(true);
if(attrs==null | | attrs.Length==0)
继续;
foreach(attrs中的属性attr)
{
if(属性为StringLengthAttribute)
{
error.errorCode=1234;
error.message=string.Format((attr作为StringLengthAttribute).error消息,prop.Name,(attr作为StringLengthAttribute.MaximumLength.ToString(),(attr作为StringLengthAttribute.MinimumLength.ToString());
error.args=新字符串[]{(attr作为StringLengthAttribute).MinimumLength.ToString(),(attr作为StringLengthAttribute.MaximumLength.ToString()};
}
}
}
返回误差;
}
以下是邮递员的测试结果:

 [HttpPost]
        public IActionResult Validate(PerInfo perInfo)
        {
            if (!ModelState.IsValid)
            {
                var error = GenerateValidationModel<PerInfo>();
                return BadRequest(error);
            }
            return Ok();
        }

        private CusError GenerateValidationModel<T>()
        {
            var error = new CusError();
            foreach (var prop in typeof(T).GetProperties())
            {
                object[] attrs = prop.GetCustomAttributes(true);
                if (attrs == null || attrs.Length == 0)
                    continue;
                foreach (Attribute attr in attrs)
                {
                    if (attr is StringLengthAttribute)
                    {
                        error.errorCode = 1234;
                        error.message = string.Format((attr as StringLengthAttribute).ErrorMessage, prop.Name, (attr as StringLengthAttribute).MaximumLength.ToString(), (attr as StringLengthAttribute).MinimumLength.ToString());
                        error.args = new string[] { (attr as StringLengthAttribute).MinimumLength.ToString(), (attr as StringLengthAttribute).MaximumLength.ToString() };
                    }

                }
            }
            return error;
        }