我们在控制器中有两个参数的主 API,但问题是即使我们将这些参数发送到 API 路径,也有一个错误说" 没有匹配的操作或方法"。所以我们很困惑如何成功调用我们的主 api,它返回响应对象中的数据。
RestService.BaseUrl = baseUrl;
var client = RestService.Instance;
var request = RestService.GetRestRequest("Payment/SyncWithIrd",
Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("application/json; charset=utf-8",
JsonConvert.SerializeObject(bmodel), ParameterType.RequestBody);
request.AddHeader("application/json; charset=utf-8",
JsonConvert.SerializeObject(mode)`enter code here`,
parameterType.RequestBody);
request.AddHeader("Content-Type", "application/json;charset=utf-8");
var response = client.Execute(request);
var value = response.Content;
return value;
我在你的代码中看到一些AddHeader,但没有一个AddBody。 常用动词 帖子有正文部分。 尝试在方法签名处添加 [FromBody],例如
[HttpPost]
public HttpResponseMessage SyncWithIrd([FromBody]BillViewModel model, [FromBody]string mode)
然后删除
request.AddHeader("application/json; charset=utf-8", JsonConvert.SerializeObject(bmodel), ParameterType.RequestBody);
request.AddHeader("application/json; charset=utf-8", JsonConvert.SerializeObject(mode)`enter code here`, parameterType.RequestBody);
然后改为添加 AddHeader
request.AddBody(new { model = JsonConvert.SerializeObject(bmodel) }, new { mode = JsonConvert.SerializeObject(mode) });
ps. 调用帖子动词时始终使用正文部分。
编辑。。
将 SyncWithIrd 的参数"字符串模式"放入 BillViewModel 中,并重建您的方法签名,如下所示:
[HttpPost]
public HttpResponseMessage SyncWithIrd([FromBody]BillViewModel model)
那么 AddBody 必须是
request.AddBody(new { model = bmodel } });
我使用类似的代码,如下所示:
var restClient = new RestClient(model.ApiUrl);
var restRequest = new RestRequest("api/auth/createuser", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddBody(new {
FullName = model.FullName,
Email = model.Email,
Username = model.UserName,
Password = model.Password
});
var restResponse = restClient.Execute(restRequest);
我希望它有所帮助。