我正在使用 ASP.NET MVC(后端是 C#),我正在嘗試發送一個看起來像這樣的 json:
{
"store_id": "store3",
"api_token": "yesguy",
"checkout_id": "UniqueNumber",
"txn_total": "10.00",
"environment": "qa",
"action": "preload"
}
到另一個網站,假設它是這樣的:
https://TestGate.paimon.com/chkt/request/request.php
通過一些研究,我發現了這一點:

uj5u.com熱心網友回復:
看起來您可能沒有正確處理asynchronous任務——WaitingForActivation您看到的訊息,而不是來自我們 API 的回應,實際上是您任務的狀態。該任務正在等待 .NET Framework 基礎結構在內部激活和調度。
看來您可能需要 await?2?任務以確保它完成或訪問回應await client.PostAsync(url, content);。要添加等待,您需要添加async到控制器?1?操作。
public async Task<ActionResult> Index(int idInsc) //Change here [1]
{
INSC_Inscription insc = GetMainModelInfos(idinsc);
JsonModel jm = new JsonModel();
jm.store_id = "store2";
jm.api_token = "yesguy";
jm.checkout_id = "uniqueId";
jm.txn_total = "123.00";
jm.environment = "qa";
jm.action = "preload";
var jsonObject = JsonConvert.SerializeObject(jm);
var url = "https://gatewayt.whatever.com/chkt/request/request.php";
HttpClient client = new HttpClient();
var content = new StringContent(jsonObject, System.Text.Encoding.UTF8, "application/json");
System.Threading.Tasks.Task<HttpResponseMessage> res = await client.PostAsync(url, content); //Change here [2]
insc.response = res.Result; // This cause an exeption
return View(insc);
}
uj5u.com熱心網友回復:
這就是我使用 Newtonsoft.Json 包、HttpClient 和 StringContent 類將 JSON 物件發布到某處的方式:
using Newtonsoft.Json;
var object = new Model
{
//your properties
}
var jsonObject = JsonConvert.SerializeObject(object);
var url = "http://yoururl.com/endpoint"; //<- your url here
try
{
using HttpClient client = new();
var content = new StringContent(jsonObject , Encoding.UTF8,
"application/json");
var res = await client.PostAsync(url, content);
}
請確保您的函式是異步的并且您等待 client.PostAsync 函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445076.html
標籤:C# json asp.net-mvc
下一篇:為什么模型不會在后期傳回控制器?
