Web API模型绑定在通用接口类型上

时间:2015-02-18 14:14:47

标签: c# asp.net-mvc asp.net-web-api asp.net-web-api2 model-binding

我有一个通用接口,代表实体的查询选项:

public interface IQueryOptions<TEntity> {
    IQueryable<TEntity> Apply(IQueryable<TEntity> query);
}

现在我想使用查询字符串将查询选项传递给WebApi路由,使用自定义模型绑定器构建IQueryOptions。

IQueryOptions可以是SortingOptions&lt;&gt;或PagingOptions&lt;&gt;,具体取决于传递给api的查询字符串

阿比

public class DummyController : ApiController {

    // optional parameter - query options are not required
    public void Test([ModelBinder]IQueryOptions<MyEntity> queryOptions = null)
    {
        ...
    }

}

Model Binder

public class QueryOptionsModelBinder : IModelBinder {
    public bool BindModel(HttpActionContext actionContext...
}

WebApi配置

var queryProvider = new SimpleModelBinderProvider(typeof(IQueryOptions<>), new QueryOptionsModelBinder());
config.Services.Insert(typeof(ModelBinderProvider), 0, queryProvider); 

我目前无法让它发挥作用。 API会引发以下错误:

Cannot create an instance of an interface.

...表示我的自定义模型绑定器永远不会被调用。没有为通用类型建模绑定工作吗?我尝试编写自己的模型绑定程序提供程序,但这也没有用。

0 个答案:

没有答案