我正在编写类似这样的测试框架:https://github.com/ivaylokenov/MyTested.WebApi但是对于ASP.NET 5 MVC 6(使用6.0.0-beta8)。
我很难尝试调用控制器的TryValidateModel来验证给定对象的ModelState。它在ASP.NET Web API 2控制器上没有任何痛苦。我应该在控制器类上实例化哪些属性,以便方法使用默认约定进行验证。无论模型和属性属性如何,我都会收到空引用异常或有效模型状态。
我已经在MVC源代码中搜索了几个小时而没有运气。我试图在控制器上设置AddMvc()服务 - 对我不起作用。我甚至试过他们的测试控制器类型位于HERE(GetController私有方法),但没有运气。以下是我目前使用的来源:
// TODO: for real this is how we configure controller?
var detailsProviders = new IMetadataDetailsProvider[]
{
new DefaultBindingMetadataProvider(new ModelBindingMessageProvider
{
MissingBindRequiredValueAccessor = name => $"A value for the '{ name }' property was not provided.",
MissingKeyOrValueAccessor = () => $"A value is required.",
ValueMustNotBeNullAccessor = value => $"The value '{ value }' is invalid.",
}),
new DefaultValidationMetadataProvider(),
new DataAnnotationsMetadataProvider(),
// new DataMemberRequiredBindingMetadataProvider(), TODO: not available in version 8 but it is in the source code of MVC
};
var compositeDetailsProvider = new DefaultCompositeMetadataDetailsProvider(detailsProviders);
var metadataProvider = new DefaultModelMetadataProvider(compositeDetailsProvider);
var httpContext = new DefaultHttpContext();
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var viewData = new ViewDataDictionary(metadataProvider, new ModelStateDictionary());
var tempData = new TempDataDictionary(new HttpContextAccessor(), new SessionStateTempDataProvider());
var bindingContext = new ActionBindingContext()
{
ModelBinder = new GenericModelBinder(),
ValueProvider = new CompositeValueProvider(new IValueProvider[0]),
InputFormatters = new List<IInputFormatter>(),
ValidatorProvider = new DataAnnotationsModelValidatorProvider(
options: null,
stringLocalizerFactory: null)
};
this.Controller.ActionContext = actionContext;
this.Controller.BindingContext = bindingContext;
this.Controller.MetadataProvider = metadataProvider;
this.Controller.ViewData = viewData;
this.Controller.TempData = tempData;
this.Controller.ObjectValidator = new DefaultObjectValidator(new IExcludeTypeValidationFilter[0], metadataProvider);
任何帮助将不胜感激。提前谢谢!
答案 0 :(得分:0)
原来它实际上是ASP.NET MVC中的一个错误,团队会为下一个RC2版本修复它:https://github.com/aspnet/Mvc/issues/3586