2016-11-14 8 views
0

私のASP.NETのWeb APIクラスは、URIからフィルタクラスにマッピングされているフィルタの様々なを持っていGETエンドポイントを持っているウェブAPIモデルバインドCSV

public IHttpActionResult List([FromUri] FilterModel filter) 

Filterクラス:

public class FilterModel { 
    public int Something {get;set;} 
    public int[] UserIds {get;set;} 
    ...lots of other properties... 
} 

私は、ユーザーIDは、カンマ区切りリストとして渡すことがしたいと思います:

http://foo.com/api/things?UserIds=1,2,3 

しかし、この中のWeb API、それは期待し:

http://foo.com/api/things?UserIds=1&UserIds=2&UserIds=3 

は、この問題を解決するための簡単な方法があります。私はカスタムモデルバインダーを作成することができますが、モデルバインディングの99%は何も変更したくありません。私の理想的な解決策は次のようなものでしょう:

public class CustomModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 

     // Access the "default" model that's created from the Uri params 
     var model = ??? 

     // Then do some work to bind the UserIds 

     return true; 
    } 
} 

アイデアはありますか?

おかげ

+0

カスタムメディアタイプフォーマッタを作成する必要があります。例:[link](http://stackoverflow.com/questions/15633402/csv-media-type-formatter-for-asp-net-web-api) –

答えて

0

これは単純すぎる場合は、わからないが、「1,2,3」のパラメータ値が(私の知る限り)唯一の文字列として渡すことができるよう、あなたが変換することstring.Splitを使用することができますintの配列に値(秒):もちろん

var userIds = Array.ConvertAll(parm.Split(','), int.Parse); 

は、そうyou'ldより良いとの変換を行い、すべてではないカンマで区切られた値が数値であるとき、FormatExceptionに実行している可能性があります複数のコード行。

希望します。