简体   繁体   English

从 ASP.NET MVC 项目后面的 C# 代码向另一个 web 站点发送 JSON 请求

[英]Send a JSON request to another web site from C# code behind in an ASP.NET MVC project

I'm working with ASP.NET MVC (backend being C#) and I'm trying to send a json that would look like this:我正在使用 ASP.NET MVC(后端是 C#),我正在尝试发送如下所示的 json:

{
    "store_id": "store3",
    "api_token": "yesguy",
    "checkout_id": "UniqueNumber",
    "txn_total": "10.00",
    "environment": "qa",
    "action": "preload"
}

to another web site, suppose it's something like:到另一个 web 网站,假设它是这样的:

https://TestGate.paimon.com/chkt/request/request.php

Through some research I found this:通过一些研究,我发现了这一点:

Send json to another server using asp.net core mvc c# 使用 asp.net 核心 mvc c# 将 json 发送到另一台服务器

Looks good but I'm not working in core, my project is just normal ASP.NET MVC.看起来不错,但我没有在核心工作,我的项目只是正常的 ASP.NET MVC。 I don't know how to use json functions to send it to a web site.我不知道如何使用 json 函数将其发送到 web 站点。

Here is what I tried (updated after inspired by Liad Dadon answer):这是我尝试过的(在 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);
}

When ths Json is posted correctly, the other web site will answer me with is own Json:当 Json 正确发布时,其他 web 网站将用自己的 Json 回答我:

{
"response" : 
    {
        "success": "true",
        "ticket": "Another_Long_And_Unique_Id_From_The_Other_Web_Site"
    }
}

What I need to do is retreive this Json answer, once I have it, the rest is piece of cake.我需要做的是检索这个 Json 答案,一旦我得到它,rest 就是小菜一碟。

Infos:信息:

After the PostAsync function, var res contains this:PostAsync function 之后,var res 包含以下内容:

在此处输入图像描述

This is how I would post a JSON object to somewhere using Newtonsoft.Json package, HttpClient and StringContent classes:这就是我使用 Newtonsoft.Json package、HttpClient 和 StringContent 类将 JSON object 发布到某个地方的方式:

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);
}

Please make sure your function is async and that you await the client.PostAsync fucntion.请确保您的 function 是异步的并且您等待 client.PostAsync 函数。

It looks like you might not be correctly handling an asynchronous task — the WaitingForActivation message you're seeing, rather than being a response from our API, is in fact the status of your task.看起来您可能没有正确处理asynchronous任务 — 您看到的WaitingForActivation消息实际上是您的任务状态,而不是来自我们的 API 的响应。 The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure.该任务正在等待 .NET 框架基础设施在内部激活和安排。
It seems you might need to await⁽²⁾ the task to ensure it completes or access the response with await client.PostAsync(url, content);看来您可能需要 await⁽²⁾ 任务以确保它完成或访问响应await client.PostAsync(url, content); . . for adding await you need to add async to controller⁽¹⁾ action.要添加等待,您需要将async添加到控制器⁽¹⁾ 操作。

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);
}

If someone is wondering how I finally pulled it off (with other's help) here it is:如果有人想知道我最终是如何(在其他人的帮助下)完成它的,那就是:

var url = "https://gatewayt.whatever.com/chkt/request/request.php";
HttpClient client = new HttpClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var content = new StringContent(jsonObject, System.Text.Encoding.UTF8, "application/json");
var res = await client.PostAsync(url, content);
var jsonRes = await res.Content.ReadAsStringAsync();

This line is important var jsonRes = await res.Content.ReadAsStringAsync();这一行很重要var jsonRes = await res.Content.ReadAsStringAsync(); the object jsonRes will be a string value, which is actually the response. object jsonRes 将是一个字符串值,实际上是响应。 The var res will only be the status of the response, not the actual response. var res将只是响应的状态,而不是实际的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Ajax 调用发送图像并在 web 方法 asp.net c# 后面传输代码 - Send Image using Ajax Call and transfer code behind web method asp.net c# 将数据从C#asp.net网站发送到已安装的C#Windows Forms应用程序 - send data from a C# asp.net web site to an installed C# windows forms app 在ASP.Net Web站点项目中混合使用VB.Net和C#代码? - Mixing VB.Net and C# Code in an ASP.Net Web Site project? 使用ASP.NET Core MVC C#将JSON发送到另一台服务器 - Send json to another server using asp.net core mvc c# 如何从C#ASP.NET Web表单背后的代码获取图表值 - How to get values of chart from code behind c# asp.net web form ASP.NET web 形式:显示值来自 c# 代码隐藏 - ASP.NET web form: display value coming from c# code-behind 如何从背后的代码绑定ASP.NET Web Forms C#应用程序中下拉列表中的“ SelectedValue”? - How to bind the 'SelectedValue' in dropdown in ASP.NET Web Forms C# application from code behind? ASP.NET C#从Code Behind设置OnSelectedIndexChanged - ASP.NET C# Set OnSelectedIndexChanged from Code Behind c#从asp.net页面访问背后的代码 - c# Code behind access from asp.net page 在C#类中使用同一ASP.NET网站项目中的VB类 - Using a VB class from the same ASP.NET web site project in a C# class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM