我有一个实体框架对象(首先是代码),所以它本质上是一个POCO。我想把它抛到WebAPI服务上(WebAPI是MVC)。
我已经成功地获得了一个简单的get调用,它使用以下命令:
Using client = New WebClient()
responseString = client.DownloadString(String.Format("http://localhost:1234/MyURLGet/{0}", txtValue.Text.Trim()))
myPOCO_Class = Newtonsoft.Json.JsonConvert.DeserializeObject(Of MyPOCO_EF_obj)(responseString)
End Using这个很好用。当我想插入数据库时,问题是试图将MyPOCO_EF_Obj附加到帖子的主体上。
到目前为止,我发现的是这一点,但它不允许我附加POCO类,只有字符串:
Using client = New WebClient()
'assemble the data
Dim values As New NameValueCollection
values("value") = txtValue.Text.Trim()
values("description") = txtDescription.Text.Trim()
Dim response = client.UploadValues("http://localhost:1234/MyURLPOST/{0}", userName), values)
retVal = Encoding.[Default].GetString(response)
End Using这段代码的问题是,当它到达另一边时,values就会被捕获,但是没有一个数据与它相匹配。
public string Post(string username, [FromBody] System.Collections.Specialized.NameValueCollection values) { //etc }我更愿意抛出POCO对象并在那里处理它,但是发送名称/值对也会有效。
尽管如此:
[FromBody]可以做到这一点吗?如果是这样的话,是怎么做的?编辑:供参考,我目前正在看这个所以的问题和答复:
发布于 2016-05-17 17:34:12
正如链接中提到的,有许多方法可以做到这一点,但是添加如何使用restSharp。使用nuget安装restsharp,创建一个简单的类如下所示
public class SampleRestClient
{
private readonly RestClient _client;
private readonly string _url = "http://xyz/"; //URL of the API
public IRestResponse Submit(SAmpleViewModel model)
{
_client = new RestClient(_url);
var request = new RestRequest("api/Submit", Method.POST) { RequestFormat = DataFormat.Json };
request.AddBody(model);
var response = _client.Execute(request);
return response;
}
} 现在,您可以在需要的地方调用Submit方法。希望这能有所帮助。
https://stackoverflow.com/questions/37279291
复制相似问题