参考:https://github.com/dotnet/runtime/blob/master/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs
参考:https://www.cnblogs.com/Cyril-hcj/p/11697871.html
参考:https://www.cnblogs.com/yeqifeng2288/p/12387638.html
1.添加MinFieldAttribute.cs实现ValidationAttribute特性类
//可用于Property(属性),Field(字段),Parameter(参数)
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class MinFieldAttribute : ValidationAttribute
{
public string MinValueField { get; set; }
private string MinDisplayName { get; set; }
private string errorMessageString;
new string ErrorMessageString//覆盖默认的错误信息String
{
get
{
if (string.IsNullOrEmpty(errorMessageString))
{
return "{0}不能小于{1}";
}
else
{
return errorMessageString;
}
}
set { errorMessageString = value; }
}
public MinFieldAttribute(string minValueField, string minDisplayName=null)// : base(operandType, minValueField, () => LocalizationExtensions.T("Rundong.Infrastructure.MinFieldAttribute.ErrorMsg", "{0}不能小于{1}"))
{
MinValueField = minValueField;
MinDisplayName = minDisplayName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var minPropertyInfo = validationContext.ObjectType.GetProperty(MinValueField);
if (minPropertyInfo == null)
{
return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "{0}不存在", MinValueField));
}
var minPropertyValue = minPropertyInfo.GetValue(validationContext.ObjectInstance, null);
var compareValue = (IComparable)value;
if (value != null && compareValue.CompareTo(minPropertyValue) < 0)
{
if (MinDisplayName == null)
{
MinDisplayName = GetDisplayNameForProperty(minPropertyInfo);
}
var result = new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
return result;
}
return null;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, MinDisplayName ?? MinValueField);
}
private string? GetDisplayNameForProperty(PropertyInfo property)
{
var attributes = CustomAttributeExtensions.GetCustomAttributes(property, true);
var display = attributes.OfType<DisplayAttribute>().FirstOrDefault();
if (display != null)
{
return display.GetName();
}
return MinValueField;
}
}
2.添加IDLog.cs在model上添加验证
public class IDLog
{
public long ID { get; set; }
public DateTime Dt { get; set; }
//[SugarColumn(IsIgnore = true)]
public DateTime startTime { get; set; }
//[SugarColumn(IsIgnore = true)]
[MinField("startTime", "开始时间",ErrorMessage = "{0}不能小于{1}")]
public DateTime endTime { get; set; }
}
3.postman测试结果
4.扩展自定义输出response的返回格式
测试拿到的数据展示是固定格式,换成我们自己的
//添加我们自己的service类
public static class ServiceExtensions
{
public static void ConfigureInvalidModelState(this IServiceCollection services)
{
services.Configure<ApiBehaviorOptions>(behavior =>
{
behavior.InvalidModelStateResponseFactory = actionContext =>
{
var errorList = actionContext.ModelState.Select(e => new
{
Field = e.Key,
ErrorMessage = e.Value.Errors?.FirstOrDefault()?.ErrorMessage
}).ToList();
errorList.RemoveAll(s => s == null || string.IsNullOrEmpty(s.ErrorMessage));
var result = new FuncResult()
{
Code = "0000",
Message = string.Join(";", errorList.Select(e => string.Format(e.ErrorMessage, e.Field)))
};
var objectResult = new ObjectResult(result);
objectResult.StatusCode = StatusCodes.Status200OK;
return objectResult;
};
});
}
}·
在startup.cs中添加
services.ConfigureInvalidModelState();