2017-02-03 77 views
4

系列化我們有多個API控制器接受像這樣的GET請求:補[FromUri]與APIController

//FooController 
public IHttpActionResult Get([FromUri]Foo f); 
//BarController 
public IHttpActionResult Get([FromUri]Bar b); 

現在 - 我們希望(或被迫)更改GET查詢字符串全球範圍內的DateTime字符串格式

"yyyy-MM-ddTHH:mm:ss" -> "yyyy-MM-ddTHH.mm.ss" 

的變化都[FromUri]序列化包含DateTime類型的類失敗後。

有沒有辦法補充[FromUri]序列化來接受查詢字符串中的DateTime格式?或者我們是否必須爲所有API參數構建自定義序列化以支持新的DateTime字符串格式?

編輯:例如根據要求

public class Foo { 
public DateTime time {get; set;} 
} 

//FooController. Let's say route is api/foo 
public IHttpActionResult Get([FromUri]Foo f); 

GET api/foo?time=2017-01-01T12.00.00 
+1

HH.MM.SS - 點是cousing擴展問題。 http://stackoverflow.com/questions/20404254/encode-email-to-pass-to-web-api – levent

+0

好吧,但那不是重點。假設您使用js,您可以將這些點替換爲 - – supertopi

+0

,您可以先將日期時間值傳遞給控制器​​,然後encodeURIComponent。然後控制器將解碼並反序列化它。 – Woot

回答

2

要應用要跨越所有車型的所有日期時間類型,這種行爲,那麼你會想要寫一個custom binder for the DateTime type and apply it globally

DateTime的模型綁定

public class MyDateTimeModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType != typeof(DateTime)) 
      return false; 

     var time = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 

     if (time == null) 
      bindingContext.Model = default(DateTime); 
     else 
      bindingContext.Model = DateTime.Parse(time.AttemptedValue.Replace(".", ":")); 

     return true; 
    } 
} 

的WebAPI配置

config.BindParameter(typeof(DateTime), new MyDateTimeModelBinder()); 
+0

感謝您的寫作,但問題是關於全局更改序列化並使用'[FromUri]',因爲多個API參數類具有多個屬性。 – supertopi

+2

您是否看到底部的DateTime模型聯編程序?它涉及全球應用行爲。我將編輯帖子以刪除解決示例代碼的示例,以便實際答案不被遮蓋。 – davidmdem