2017-03-02 1 views
1

WebServiceが[FromUri]パラメータで受け取った複合型(クラス)から解析しようとしたときに、いくつかのプロパティがバインドされる方法をカスタマイズしたいと思います。Web Api 2でFromUriで受け取った解析をカスタマイズするにはどうすればよいですか?

制御方法

[HttpGet] 
[Route("Test")] 
public IHttpActionResult ComplexPropertiesTest([FromUri] MyComplexPropertiesClass parameters) 

クラス

public class MyComplexPropertiesClass 
    { 
     public DateTime TestTime { get; set; } 

     public IEnumerable<int> TestIntEnumeration { get; set; } 

     public int SimpleInt { get; set; } 

     public string SimpleString { get; set; } 

     // More properties... 
    } 

yyyyMMddTHHmmss日付形式と時間だけで文字列から解析される必要があるTestTimeHHmmssが格納されなければなりません。

TestEnumerationは、5,20,50,100,9のような文字列として受け取ることができ、IEnumerable[int]として格納する必要があります。 URLの

例:

http://www.example.com/test?TestTime=20170303T091500&TestEnumeration=5,20,50,100,9. 

私はhttp://www.vickram.me/custom-datetime-model-binding-in-asp-net-web-api/HttpParameterBindingアプローチを試みたが、それは私のようなものに、コントローラのメソッドを変更する場合にのみ機能します:

public IHttpActionResult ComplexPropertiesTest ([ModelBinder(typeof(CommaSeparatedIntegerCollectionModelBinder))] IEnumerable<int> TestIntEnumeration, …all the other parameters…)` 

しかし、これではありません新しい解決法は、新しいMyComplexPropertiesClassインスタンスのプロパティにすべての引数を手動で割り当てるようにコントローラを変更する必要があるためです。

また、私はbindingContext.ModelNameでparametersを受けるhttp://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/

internal class CustomModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     if (val?.AttemptedValue == null) 
     { 
      return false; 
     } 
    } 
} 

CommaDelimitedCollectionModelBinderアプローチを試みたしましたが、論理的にMyComplexPropertiesClassにはValueProviderはありません。 actionContext.Request.RequestUri.Queryの値を取得しようとする可能性がありますが、手動ですべてのプロパティを解析し、反映を使用してMyComplexPropertiesClassという新しいインスタンスに値を割り当てる必要があります。残念ながらデフォルトのWeb Api 2バインディングプロセスを利用して、手動で必要なものを解析することをお勧めします。

お願いします。

+0

あなた自身のJsonConverterの作成を試みましたか?この記事は、次のような場合に役立ちます:http://blogs.microsoft.co.il/miziel/2014/09/23/custom-web-api-json-converter-single-property/ また、私はインターフェイスが常に動作しないことに気付きましたIEnumerableをListまたはArrayに変更しようとしました – owczarek

+0

あなたは[what](http://stackoverflow.com/help/mcve)を共有してみませんか? –

+0

私はJSONアプローチを試みましたが、コンテンツがJSONではないためカスタムシリアライザは起動しません。内容は '[FromUri]'パラメータから来ます。 @SergeyShushlyapin私はすでに試したことを示すために私の答えを更新しました。 – Dave

答えて

0

は、ここでのDateTimeと似たようなケースである:

Complement [FromUri] serialization with APIController

欠点は、それがすべてのDateTimeプロパティに適用されています。この動作を使用するプロパティを選択することはできません。どちらも、TestEnumerationの問題を解決しません。

関連する問題