我在HttpApi.Host项目的XxxHttpApiHostModule类的ConfigureServices方法添加如下代码:
context.Services.AddMvc(options =>
{
options.Filters.Add<ValidateFilter>();
});
然后自己写了一个过滤器
/// <summary>
/// 方法统一过滤器
/// </summary>
public class ValidateFilter : IActionFilter
{
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var result = new ResponseModel();
foreach (var item in context.ModelState.Values)
{
if (item.ValidationState == ModelValidationState.Invalid)
{
result.Code = 500;
result.Message = item.Errors.FirstOrDefault().ErrorMessage;
break;
}
}
context.Result = new JsonResult(result);
}
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
如上写了不起作用,求大神指点。
这个可能不是最优解决方法,但是目前没想到其它方式,暂时这么解决。
只需要做两件事情:
1.将源码中的类:ModelStateValidator,直接拷贝过来
2.修改public virtual void Validate(ModelStateDictionary modelState)方法,在方法体头部直接return。意思就是不走下面的逻辑了
具体代码如下:
public class ModelStateValidator : IModelStateValidator, ITransientDependency
{
public virtual void Validate(ModelStateDictionary modelState)
{
return;
//var validationResult = new AbpValidationResult();
//AddErrors(validationResult, modelState);
//if (validationResult.Errors.Any())
//{
// throw new AbpValidationException(
// "ModelState is not valid! See ValidationErrors for details.",
// validationResult.Errors
// );
//}
}
public virtual void AddErrors(IAbpValidationResult validationResult, ModelStateDictionary modelState)
{
if (modelState.IsValid)
{
return;
}
foreach (var state in modelState)
{
foreach (var error in state.Value.Errors)
{
validationResult.Errors.Add(new ValidationResult(error.ErrorMessage, new[] { state.Key }));
}
}
}
}
还有一种简单的方式,就是在ConfigureServices方法里面,添加如下代码:
context.Services.AddMvc(options =>
{
options.Filters.Add(typeof(ValidateFilter), -1);
});
options.Filters.Add方法的第二个参数表示排序,设为0或1或者更大都会先走AbpValidationActionFilter。当我尝试设置为-1时竟然不走AbpValidationActionFilter了。完美解决。