2017-08-02 60 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