如何在WebAPI中将可变数量的参数传递给GET

pri*_*fan 0 c# asp.net asp.net-web-api

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

public HttpResponseMessage Get( string where_name, 
                                IndexFieldsModel index_fields = null )

public class IndexFieldsModel
{
    public List<IndexFieldModel> Fields { get; set; }
}

public class IndexFieldModel
{
    public string Name { get; set; }
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的API.我的问题是index_fields是名称值对的集合,它是可选的和可变长度.问题是我不知道将提前传递给我的GET方法的名称.一个示例电话是:
/api/workitems?where_name=workitem&foo=baz&bar=yo

IModelBinder是走这里的方式,还是有更简单的方法?如果是IModelBinder我如何遍历名称?我去这里看一个IModelBinder的例子:http: //www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api 但是我没有看到一种迭代名称的方法,并选择"foo"和"bar".

我尝试将index_fields更改为Dictionary<string, string>没有IModelBinding,但没有做任何事情:index_fields为null.当我在做IModelBinder并调试我的IModelBinder.BindModel例程时,如果我深入查看ModelBindingContext对象,我可以在其中看到"foo"和"bar"值System.Web.Http.ValueProviders.Providers.QueryStringValueProvider,但我不知道如何使用它.我尝试从头创建一个QueryStringValueProvider但它需要一个HttpActionContext.再一次,我没有看到迭代通过键获得"foo"和"bar"的方法.

顺便说一句:我正在使用VS2012

Mot*_*Azu 10

您可以简单地遍历查询参数

public ActionResult Method()
{
    foreach(string key in Request.QueryString) 
    {
        var value = Request.QueryString[key];
    }
}
Run Code Online (Sandbox Code Playgroud)