我正在使用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通过一些研究我发现:
使用asp.net核心mvc c#将json发送到另一个服务器
看起来不错,但我不是在核心工作,我的项目只是普通的ASP.NET MVC。我不知道如何使用json函数将其发送到网站。
下面是我尝试过的(在Liad Dadon回答的启发下更新的):
public ActionResult Index(int idInsc)
{
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 = client.PostAsync(url, content);
insc.response = res.Result; // This cause an exeption
return View(insc);
}当Json正确发布时,另一个网站将用它自己的Json回答我:
{
"response" :
{
"success": "true",
"ticket": "Another_Long_And_Unique_Id_From_The_Other_Web_Site"
}
}我需要做的是收回这个Json的回答,一旦我得到了它,剩下的就是小菜一碟了。
信息:
在PostAsync函数之后,var res包含以下内容:

发布于 2022-03-15 09:15:32
看起来您可能没有正确地处理asynchronous任务--您正在看到的WaitingForActivation消息,而不是来自我们API的响应,实际上就是您的任务的状态。该任务正在等待由.NET框架基础结构在内部激活和调度。
您可能需要等待任务的⁽2⁾来确保它完成或使用await client.PostAsync(url, content);访问响应。要添加等待,需要将async添加到控制器⁽1 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);
}发布于 2022-03-11 20:37:07
这就是我如何使用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://stackoverflow.com/questions/71443966
复制相似问题