【发布时间】:2020-12-03 17:32:25
【问题描述】:
我在服务器端使用以下代码调用 API。它不断带来错误:无法解析请求正文。确保请求正文匹配指定的内容类型:application/json
服务器端代码如下:
[HttpPost]
public async Task<JsonResult> BVNMatch()
{
var secretKey = ConfigurationManager.AppSettings["paystack_SecretKey"];
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.paystack.co/bvn/match"))
{
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {secretKey}");
request.Content = new StringContent("{ bvn: \"22******\",\n account_number: \"068*****\",\n bank_code: \"034\",\n first_name: \"uth***\",\n last_name: \"ji***\"\n }");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
var jsonString = await response.Content.ReadAsStringAsync();
BVNMatch myDeserializedClass = JsonConvert.DeserializeObject<BVNMatch>(jsonString);
return Json(myDeserializedClass);
}
}
}
下面是客户端的 Ajax 调用:
// Testing the BVNMatch Paystack API
$("#btnGetBVN").click(function () {
if ($('#BVN').val() == '' || $('#BVN').val() == undefined) {
alert('Please Enter Customer BVN');
return false;
}
$('.spinner').css('display', 'block'); //if clicked ok spinner shown
$.ajax({
type: "POST",
url: "@Url.Action("BVNMatch", "Transactions")",
// data: '{bvn: "' + $("#BVN").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.message);
$('#Firstname').val(response.data.bvn);
$('#Surname').val(response.data.is_blacklisted);
// $('#Phone_Number').val(response.data.mobile);
$('.spinner').css('display', 'none');
},
failure: function (response) {
alert('BVN Does Not Exist Or Error Processing Request');
$('.spinner').css('display', 'none');
},
error: function (response) {
alert('BVN Does Not Exist Or Error Processing Request');
$('.spinner').css('display', 'none');
}
});
});
【问题讨论】:
-
@david,你能帮忙吗?
-
通过将 json 内容作为字符串解决的问题
标签: c# json ajax asp.net-mvc json.net