【发布时间】:2018-06-10 03:13:19
【问题描述】:
我有一个 Web Api Model Binder,如下所示:
public class KeyModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//...
}
}
我正在尝试编写规则以使其更易于测试。我找到了一个可以与 MVC 的模型绑定器 here 一起使用的函数:
但在尝试转换为使用 webApi 时,我无法弄清楚如何填充值提供者
public TModel BindModel<TBinder, TModel>(NameValueCollection formCollection, TBinder binder)
where TBinder : IModelBinder
{
var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
var dataProvider = new DataAnnotationsModelMetadataProvider();
var modelMetadata = dataProvider.GetMetadataForType(null, typeof(TModel));
var bindingContext = new ModelBindingContext
{
ModelName = typeof(TModel).Name,
ValueProvider = valueProvider,
ModelMetadata = modelMetadata
};
binder.BindModel(null, bindingContext);
return (TModel)bindingContext.ModelMetadata.Model;
}
NameValueCollection 仅存在于 MVC 中,如何为 Web-Api 创建值提供者
【问题讨论】:
标签: c# asp.net-mvc unit-testing asp.net-web-api model-binding