测试Web Api模型绑定器

问题描述 投票:0回答:1

我有一个Web Api Model Binder,看起来像这样:

public class KeyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {  
     //...
    }
}

我正在尝试编写一条规则,以便更容易测试。我找到了一个与MVC的模型绑定器here一起使用的函数:

但是当试图转换为使用web Api时,我无法弄清楚如何填充值提供者

    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
1个回答
0
投票

它没有使用默认值提供程序来测试模型绑定器。所以我根据预期的规则编写了我的绑定模型。在这种情况下,我只需要测试获取

public TModel BindModelFromGet<TBinder, TModel>(string modelName, string queryString, TBinder binder)
    where TBinder : IModelBinder
{
    var httpControllerContext = new HttpControllerContext();
    httpControllerContext.Request = new HttpRequestMessage(HttpMethod.Get, MOCK_URL + queryString);
    var bindingContext = new ModelBindingContext();

    var dataProvider = new DataAnnotationsModelMetadataProvider();
    var modelMetadata = dataProvider.GetMetadataForType(null, typeof(TModel));

    var httpActionContext = new HttpActionContext();
    httpActionContext.ControllerContext = httpControllerContext;

    var provider = new QueryStringValueProvider(httpActionContext, CultureInfo.InvariantCulture);

    bindingContext.ModelMetadata = modelMetadata;
    bindingContext.ValueProvider = provider;
    bindingContext.ModelName = modelName;

    if (binder.BindModel(httpActionContext, bindingContext))
    {
        return (TModel)bindingContext.Model;
    }

    throw new Exception("Model was not bindable");
}

如果你想让它适用于post你接受一个jsonValues字符串修改httpControllerContext,如下所示:

httpControllerContext.Request = new HttpRequestMessage(HttpMethod.Post, "");
httpControllerContext.Request.Content = new ObjectContent<object>(jsonValues, new JsonMediaTypeFormatter());

然后你只需要使用正确的ValueProvider(我没有研究如何,因为它不需要我)。

© www.soinside.com 2019 - 2024. All rights reserved.