[英]PostAsync parameter is always null
I am calling an API Post method, however, I am not sure what I am doing wrong but the value in the API is always null.我正在调用 API Post 方法,但是,我不确定我做错了什么,但 API 中的值始终为空。 The method I am calling the API from is below.我正在调用 API 的方法如下。 When I hit this I can see Ids is list of ints with 5 values for example.当我点击这个时,我可以看到 Ids 是具有 5 个值的整数列表。
private void Save(List<int> Ids)
{
var myAPI = ConfigurationManager.AppSettings["MyAPI"];
string myIds = string.Join(",", Ids);
using (var client = new HttpClient())
{
int result = client.PostAsync(myAPI, new { test = myIds }, new JsonMediaTypeFormatter())
.Result
.Content
.ReadAsAsync<int>()
.Result;
}
}
My API signature is like below - with a breakpoint on I can see it is getting hit but test the parameter I am trying to pass is always null我的 API 签名如下 - 有一个断点,我可以看到它被击中,但测试我试图传递的参数始终为空
[HttpPost]
[Route("api/MyController/SaveData")]
public HttpResponseMessage SaveData([FromBody]List<string> test)
{
try
{
//Rest of method removed for brevity
I have tried removing the [FromBody] Annotation from the WebAPI controller but test still is getting null with breakpoint in the SaveData API method我曾尝试从 WebAPI 控制器中删除 [FromBody] 注释,但测试仍然使用 SaveData API 方法中的断点获取空值
Try this:尝试这个:
private void Save(List<int> Ids)
{
var myAPI = ConfigurationManager.AppSettings["MyAPI"];
using (var client = new HttpClient())
{
var requestBody = JsonConvert.SerializeObject(Ids);
var postRequest = new StringContent(requestBody, Encoding.UTF8, "application/json");
var response = client.PostAsync(myAPI, postRequest).GetAwaiter().GetResult();
var rawResponse = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
// Do something with the answer
}
}
I also suggest to make the method private Task Save
and replace .GetAwaiter().GetResult();
我还建议将方法设为private Task Save
并替换.GetAwaiter().GetResult();
with await
in front of that calls.在那个电话前面await
。
In my case i used System.Web.Http.ApiController instead of System.Web.Mvc.Controller.就我而言,我使用 System.Web.Http.ApiController 而不是 System.Web.Mvc.Controller。 So over all code looks like所以所有的代码看起来像
public class YourAppController : ApiController
{
[System.Web.Http.Route("publish-message")]
public HttpResponseMessage Post([System.Web.Http.FromBody] string msges)
{
//Your Code
return Request.CreateResponse(HttpStatusCode.OK, "");
}
}
public async Task<string> PublishMessageCall(string publishMessage){
var returnval = "";
string httpWebRqst = "http://localhost:543134535/publish-message";
using (HttpClient myClient = new HttpClient())
{
var jsonString = JsonConvert.SerializeObject(publishMessage);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await myClient.PostAsync(httpWebRqst, content);
var responseString = await response.Content.ReadAsStringAsync();
}
return await Task.FromResult(returnval);}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.