1.添加过滤器
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(
new ApiResult
{
StatusCode = 0,
Message = actionContext.ModelState.Values.ToList().Select(it=>it.Errors.Select(i=>i.ErrorMessage)).ToJson()
})
)
};
}
}
2.定义Model并添加验证规则
[EnumDefinedAttribute(typeof(SettleAccountType))]//自已写的枚举验证
public SettleAccountType MemberType { get; set; }
[Required(ErrorMessage = "锁定对象ID不能为空")]
[MinLength(6, ErrorMessage = "最小长度不能小于6")]
public string MemberID { get; set; }
[EnumDefinedAttribute(typeof(LockEvent))]//自已写的枚举验证
public LockEvent LockEvent { get; set; }
3.为Controller或 Action 添加特性(此处未注册全局过滤器那边,按需添加的)
[ValidateModel]
public class UserLockController : BaseController
{
}