具有复杂数组参数的Web API

时间:2015-04-29 19:26:26

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

需要这方面的帮助。我有一个WebAPI谁可以接收多个ID作为参数。用户可以使用2路径调用API:

第一条路线:

api/{controller}/{action}/{ids}

ex: http://localhost/api/{controller}/{action}/id1,id2,[...],idN

方法签名

public HttpResponseMessage MyFunction(
    string action, 
    IList<string> values)

第二条路线:

"api/{controller}/{values}"

ex: http://localhost/api/{controller}/id1;type1,id2;type2,[...],idN;typeN

public HttpResponseMessage MyFunction(
    IList<KeyValuePair<string, string>> ids)

现在我需要将一个新参数传递给现有的2条路线。问题是这个参数是可选的并且与id值紧密相关。我做了一些尝试,就像使用KeyValuePair的方法进入KeyValuePair参数,但是它导致了路由之间的一些冲突。

我需要的是这样的东西:

ex: http://localhost/api/{controller}/{action}/id1;param1,id2;param2,[...],idN;paramN

http://localhost/api/{controller}/id1;type1;param1,id2;type2;param2,[...],idN;typeN;paramN

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

首先,我创建了一个覆盖

的类
KeyValuePair<string, string>

键入以添加第三个元素(我知道它并不是真正的一对!)。我也可以使用Tuple类型:

 public sealed class KeyValuePair<TKey, TValue1, TValue2>
    : IEquatable<KeyValuePair<TKey, TValue1, TValue2>>

要将此类型与参数一起使用,我创建一个

  

ActionFilterAttribute

分割(&#34;;&#34;)url中的值并创建KeyValuePair(第三个元素是可选的)

 public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ActionArguments.ContainsKey(ParameterName))
        {
            var keyValuePairs = /* function to split parameters */;

            actionContext.ActionArguments[ParameterName] = 
                keyValuePairs.Select(
                    x => x.Split(new[] { "," }, StringSplitOptions.None))
                        .Select(x => new KeyValuePair<string, string, string>(x[0], x[1], x.Length == 3 ? x[2] : string.Empty))
                        .ToList();                
        }
    }

最后,我将action属性过滤器添加到控制器路由并更改参数类型:

"api/{controller}/{values}"

ex: http://localhost/api/{controller}/id1;type1;param1,id2;type2,[...],idN;typeN;param3

[MyCustomFilter("ids")]
public HttpResponseMessage MyFunction(
    IList<KeyValuePair<string, string, string>> ids)

我可以使用一些url解析技术,但是ActionFilterAttribute很棒,而且代码最终不是一团糟!