2014-10-30 38 views
0

請求有效負載不會被轉換爲自定義請求對象。Web API參數綁定

有效載荷

appl5=MC~IC&i~PhoneToPhone~inet_ptt_cb_phn~1=440&inet_ptt_cb_phn~3=7406&i~PhoneToPhone~inet_ptt_cb_delay=0&BeenHere=TRUE 

它〜在密鑰值對(無論是在鍵和值)。

我有一個請求模型,將輸入參數轉換爲無效的對象。

注意:我不能在我的C#屬性中。 (可以嗎?)

我Post方法具有下面的代碼

public HttpResponseMessage Post(ClientRequest request) 
    { 
     HttpResponseMessage response; 

     try 
     { 
      ProcessRequest target = new ProcessRequest(myRepository, myService); 
      response = target.Process(request); 

     } 
     catch (Exception exception) 
     { 
      response = Request.CreateErrorResponse(HttpStatusCode.NotFound, exception.Message); 
      //TODO : Log Exception. 
     } 

     return response; 
    } 

型號

public class ClientRequest  
{ 
     public string Appl5 { get; set; } 
     public string I_PhoneToPhone_inet_ptt_cb_phn_1 { get; set; } 
     public string I_PhoneToPhone_inet_ptt_cb_delay { get; set; } 
     public string Inet_ptt_cb_phn_3 { get; set; } 
     public string BeenHere { get; set; } 

}

我的請求對象不具有值I〜PhoneToPhone〜inet_ptt_cb_phn 〜1,其無效。

我的理解是模型綁定是不會發生,因爲有效載荷密鑰不匹配 與我的模型(的ClientRequest),它沒有〜因爲我〜PhoneToPhone〜inet_ptt_cb_phn〜1 在代替我有i_PhoneToPhone_inet_ptt_cb_phn_1

我應該使用自定義綁定?

+0

我個人只是改變我的模型屬性名稱駱駝的情況下,避免頭痛。 – 2014-10-30 21:00:24

+0

我不認爲改變駱駝案件會起作用。 – srieen 2014-10-31 14:21:32

+0

最後,我可以通過添加Costom Binder – srieen 2014-11-01 01:17:13

回答

0

最後,添加了自定義模型綁定

公共類PostParameterModelBinder:IModelBinder {

bool IModelBinder.BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     bool success = false; 

     if (bindingContext.ModelType == typeof(ClientRequest)) 
     { 
      NameValueCollection postData = null; 

      postData = actionContext.Request.Content.ReadAsFormDataAsync().Result; 

      ClientRequest clientrequest = MapPostDataToRequest(postData); 

      bindingContext.Model = clientrequest; 

      success = true; 
     } 

     return success; 
    } 
} 

}