2016-12-13 2 views
0

私のDateTimeオブジェクトにはミリ秒の精度が必要なため、WindowsサービスからWebApiにTicksを送信しています。これは、APIへの私のコールで、最後のパラメータは、要求が次のようになり、コントローラに当たる日時WebApiルートパラメータのティックをDateTimeにバインド

V1 /製品/ 2/1/1000/APIの6361494347.747億

です:

[Route("api/v1/Product/{site}/{start?}/{pageSize?}/{from?}")] 
public IHttpActionResult Product(Site site, int start = 1, int pageSize = 100, DateTime? fromLastUpdated = null) 

デフォルトのモデルバインダーは、ティックをDateTimeパラメータにバインドできません。任意のヒントをいただければ幸いです。

答えて

1

使用long fromLastUpdatedparsecast to DateTime独立

[Route("api/v1/Product/{site}/{start?}/{pageSize?}/{from?}")] 
public IHttpActionResult Product(Site site, int start = 1, int pageSize = 100, long? fromLastUpdated = null) 
{ 
    if (fromLastUpdated.HasValue) 
    { 
     var ticks = fromLastUpdated.Value; 
     var time = new TimeSpan(fromLastUpdated); 
     var dateTime = new DateTime() + time; 
     // ... 
    } 
    return ... 
} 
0
  1. あなたが次のルートV1 /製品/ 2/1/1000/2016-11-17T01でそれを呼び出すことができます:37:57.4700000。モデルバインディングは正しく動作します。

  2. それとも、カスタムモデルバインダー定義することができます。

    public class DateTimeModelBinder : System.Web.Http.ModelBinding.IModelBinder 
    { 
        public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext) 
        { 
         if (bindingContext.ModelType != typeof(DateTime?)) return false; 
    
         long result; 
    
         if (!long.TryParse(actionContext.RequestContext.RouteData.Values["from"].ToString(), out result)) 
          return false; 
    
         bindingContext.Model = new DateTime(result); 
    
         return bindingContext.ModelState.IsValid; 
        } 
    } 
    
    [System.Web.Http.HttpGet] 
    [Route("api/v1/Product/{site}/{start?}/{pageSize?}/{from?}")] 
    public IHttpActionResult Product(Site site, 
               int start = 1, 
               int pageSize = 100, 
               [System.Web.Http.ModelBinding.ModelBinderAttribute(typeof(DateTimeModelBinder))] DateTime? fromLastUpdated = null) 
    { 
        // your code 
    } 
    
関連する問題