我在服务器端使用以下代码调用 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');
}
});
});
通过在内容 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);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句