简体   繁体   中英

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:

{
    "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:

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#

Looks good but I'm not working in core, my project is just normal ASP.NET MVC. I don't know how to use json functions to send it to a web site.

Here is what I tried (updated after inspired by Liad Dadon answer):

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:

{
"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.

Infos:

After the PostAsync function, var res contains this:

在此处输入图像描述

This is how I would post a JSON object to somewhere using Newtonsoft.Json package, HttpClient and StringContent classes:

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.

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. The task is waiting to be activated and scheduled internally by the .NET Framework infrastructure.
It seems you might need to await⁽²⁾ the task to ensure it completes or access the response with await client.PostAsync(url, content); . for adding await you need to add async to controller⁽¹⁾ action.

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(); the object jsonRes will be a string value, which is actually the response. The var res will only be the status of the response, not the actual response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM