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
日付形式と時間だけで文字列から解析される必要があるTestTime
部HHmmss
が格納されなければなりません。
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バインディングプロセスを利用して、手動で必要なものを解析することをお勧めします。
お願いします。
あなた自身のJsonConverterの作成を試みましたか?この記事は、次のような場合に役立ちます:http://blogs.microsoft.co.il/miziel/2014/09/23/custom-web-api-json-converter-single-property/ また、私はインターフェイスが常に動作しないことに気付きましたIEnumerableをListまたはArrayに変更しようとしました – owczarek
あなたは[what](http://stackoverflow.com/help/mcve)を共有してみませんか? –
私はJSONアプローチを試みましたが、コンテンツがJSONではないためカスタムシリアライザは起動しません。内容は '[FromUri]'パラメータから来ます。 @SergeyShushlyapin私はすでに試したことを示すために私の答えを更新しました。 – Dave