覆盖 ValidationAttribute ErrorMessage,从字符串到新的 ErrorModel Class

Override ValidationAttribute ErrorMessage, from string to new ErrorModel Class

我目前正在学习 Net Core,谁能与我分享如何将 dataAnnotation ErrorMessage 从字符串重写为对象。

而不是 ErrorMessage 作为字符串

[RegularExpression(@"^[a-zA-Z0-9._-]{3,15}$", ErrorMessage = "Please make sure username is between 3 to 15 character and may also contain '._-' special character only.")]
public string Username { get; set; }

将 ErrorMessage 作为对象

[RegularExpression(@"^[a-zA-Z0-9._-]{3,15}$", ErrorMessage = new ErrorModel { MESSAGE = "Something went wrong when updating username.Please contact system admin if issue persist.", STATUS_CODE = "1"})]
public string Username { get; set; }

我创建了一个 ErrorModel class

public class ErrorModel
{
    public string STATUS_CODE { get; set; }
    public string MESSAGE { get; set; }
}

我想为从 ValidationAttribute 派生的所有属性覆盖从字符串到对象的 ErrorMessage,这可行吗?

此致, 哈兹敏

RegularExpressionAttribute继承自ValidationAttributeErrorMessage没有用abstract或virtual声明,因此无法扩展或修改。

根据您的情况,您希望显示包含消息和状态代码的错误消息,您可以自定义如下响应:

型号:

public class ErrorModel
{
    public string Key { get; set; }
    public string STATUS_CODE { get; set; }
    public string MESSAGE { get; set; }
}
public class Test
{

    [RegularExpression(@"^[a-zA-Z0-9._-]{3,15}$")]
    public string Username { get; set; } 
    //other properties
}

控制器:

[HttpPost]
public async Task<IActionResult> Create(Test model)
{
    if (ModelState.IsValid)
    {               
       //...
    }
    var errorList = new List<ErrorModel>();
    //1.foreach the key
    foreach (var modelStateKey in ModelState.Keys)
    {
        var modelStateVal = ModelState[modelStateKey];
        //2.check if this key contains error
        foreach (var error in modelStateVal.Errors)
        {
            var key = modelStateKey;
            if (key == "Username")
            {
                errorList.Add(new ErrorModel { Key = key, MESSAGE = "Something went wrong when updating username.Please contact system admin if issue persist.", STATUS_CODE = "1" });                       
            }
            else {
                errorList.Add(new ErrorModel { Key = key, MESSAGE = error.ErrorMessage, STATUS_CODE = "1" });
            }
        }                
    }
    return BadRequest(errorList);
}