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

时间:2021-12-12 04:19:30
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; }
}

This is my API. My problem is the index_fields is a collection of name value pairs, which is optional and variable length. The thing is I don't know the names that will be passed to my GET method ahead of time. An example call is:
/api/workitems?where_name=workitem&foo=baz&bar=yo

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

Is IModelBinder the way to go here, or is there a simpler approach? If it's IModelBinder how do I iterate through the names? I went here to see an example of IModelBinder: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api But I don't see a way to iterate through the names and pick out "foo" and "bar".

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

I tried changing index_fields to Dictionary<string, string> and no IModelBinding but that did nothing: index_fields was null. When I'm doing IModelBinder and debugging my IModelBinder.BindModel routine, if I drill down into the ModelBindingContext object, I can see the "foo" and "bar" values in the System.Web.Http.ValueProviders.Providers.QueryStringValueProvider, but I don't know how to use that. I tried creating a QueryStringValueProvider from scratch but it takes an HttpActionContext. Again, I don't see a way to iterate through the keys to get "foo" and "bar".

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

BTW: I'm using VS2012

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

1 个解决方案

#1


5  

You can simply iterate through the query parameters

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

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

#1


5  

You can simply iterate through the query parameters

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

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