我使用Fluent Validation和MVC过滤器来验证请求。作为错误的一部分,我想显示一个有效值的列表。我不知道如何像验证过滤器填充FieldNam
e和Message
那样,用有效值列表填充ValidValues
属性。
当前错误消息如下:
{
"errors": [
{
"fieldName": "Make",
"message": "Invalid Make"
}
]
}
我想让它显示这样的东西:
{
"errors": [
{
"fieldName": "Make",
"message": "Invalid Make",
"validValues": ["Ford", "Honda"]
}
]
}
我的错误模型:
public class Error
{
public string FieldName { get; set; }
public string Message { get; set; }
public string[] ValidValues { get; set; }
}
验证器:
RuleFor(car => car.Make)
.Must(BeAValidMake)
.WithMessage("Invalid Make.");
//Add Valid values some how so they can be used by the validation filter to populate the error model.
验证过滤器:
public class ValidationFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
var errorsInModelState = context.ModelState
.Where(x => x.Value.Errors.Count > 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => e.ErrorMessage)).ToArray();
var errorResponse = new ErrorResponse();
foreach (var error in errorsInModelState)
{
foreach (var subError in error.Value)
{
var errorModel = new Error()
{
FieldName = error.Key,
Message = subError
};
errorResponse.Errors.Add(errorModel);
}
}
context.Result = new BadRequestObjectResult(errorResponse);
return;
}
await next();
}
}
我还没有找到任何内置属性等,这会很有帮助,但快速解决方案是这样的,
public class InputModelValidator : AbstractValidator<InputModel>
{
public InputModelValidator()
{
RuleFor(x => x.Name)
.Length(1, 10);
RuleFor(x => x.Email)
.EmailAddress()
.WithMessage("My Error Message %Split% Possible Values");
}
}
你的行动过滤器会是这样的,
public class ValidationFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
var errorsInModelState = context.ModelState
.Where(x => x.Value.Errors.Count > 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => e.ErrorMessage)).ToArray();
var errorResponse = new ErrorResponse();
foreach (var error in errorsInModelState)
{
foreach (var subError in error.Value)
{
var errorModel = new Error()
{
FieldName = error.Key,
Message = subError.Split("%Split%")[0],
ValidValues = subError.Split("%Split%")[1],
};
errorResponse.Errors.Add(errorModel);
}
}
context.Result = new BadRequestObjectResult(errorResponse);
return;
}
await next();
}
}
示例响应
{
"errors": [
{
"fieldName": "Email",
"message": "My Error Message ",
"validValues": " Possible Values"
}
]
}