【问题标题】:How do I pass variable number of arguments to GET in WebAPI如何在 WebAPI 中将可变数量的参数传递给 GET
【发布时间】:2014-12-24 22:33:00
【问题描述】:
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; }
}

这是我的 API。我的问题是 index_fields 是名称值对的集合,它是可选的和可变长度的。问题是我不知道将提前传递给我的 GET 方法的名称。一个示例调用是:
/api/workitems?where_name=workitem&amp;foo=baz&amp;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&lt;string, string&gt; 并且没有 IModelBinding,但什么也没做: index_fields 为空。当我在做 IModelBinder 和调试我的 IModelBinder.BindModel 例程时,如果我深入到 ModelBindingContext 对象,我可以看到System.Web.Http.ValueProviders.Providers.QueryStringValueProvider 中的“foo”和“bar”值,但我不知道如何使用那。我尝试从头开始创建一个 QueryStringValueProvider,但它需要一个 HttpActionContext。同样,我没有看到一种方法可以遍历键来获取“foo”和“bar”。

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

【问题讨论】:

标签: c# asp.net asp.net-web-api


【解决方案1】:

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

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

【讨论】:

  • 效果很好,虽然我必须使用Request.GetQueryNameValuePairs。没有Request.QueryString。谢谢! (我会投票赞成你的答案,但我没有足够的声誉 - 抱歉)
猜你喜欢
  • 2020-09-11
  • 1970-01-01
  • 2010-11-06
  • 2011-10-09
  • 1970-01-01
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多