2017-08-02 63 views
0

我有一個類如下的WebAPI定製模型綁定

class myClass{ 
    string name; 
    MyCustomType value; 
} 

的WebAPI Contrller操作方法爲:

public string AddStudent([FromBody] myClass model) 
{ 
//code implementation; 
} 

現在怎麼設置MyCustomType時傳遞addStudent動作被調用。我試圖編寫一個模型綁定器,但它試圖設置像myClass一樣的整個模型。我想要的是編寫一個通用綁定器,它將綁定從http post body傳遞給MyCustomType的值。

回答

0

我發佈了下面的完整代碼,並使用fiddler將數據發佈到「AddStudent」操作方法。它將響應作爲屬於「MyCustomType」類的「CustomField」的值。如果遇到任何問題,請告知我們?

型號:

public class MyClass 
    { 
     public string name; 
     public MyCustomType value; 
    } 


    public class MyCustomType 
    { 
     public string CustomField { get; set; } 
    } 

控制器:

 [HttpPost] 
    public HttpResponseMessage AddStudent([FromBody]MyClass model) { 

     return new HttpResponseMessage() 
     { 
      Content = new StringContent(model.ToString(), Encoding.UTF8, "text/html") 
     }; 

    } 

菲德勒POST請求:

Post the data using fiddler

+0

謝謝你的回覆... myCustomType實際上是myClass的一個屬性。所以當綁定發生時,我如何在myClass類的myCustomType中設置值 – user321963

+0

上面編輯了我的答案。請檢查並讓我知道它是否適合您。 – SailajaPalakodeti