2

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 :

enter image description here

Antoine Pelletier
  • 3,164
  • 3
  • 40
  • 62
  • `HttpClient` class is the right API that you are looking for. See this link. https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0 – ibubi Mar 11 '22 at 19:56
  • Yes this answers a good part of the question, thank you, it will allow me to send something to the other web site, the Json part though... – Antoine Pelletier Mar 11 '22 at 20:09
  • What is the exception you're getting? – Liad Mar 14 '22 at 18:31
  • Expectation is the other web site is going to answer me with is own JSON that format will be like the code block before the last one. Maybe the order of my explanations is a bit confusing, i'll reformulate and also will add an image of res – Antoine Pelletier Mar 14 '22 at 19:28
  • @LiadDadon reformulated my question so the goal is clear, also added the content of res var – Antoine Pelletier Mar 14 '22 at 19:36
  • is because you using method async, change ` System.Threading.Tasks.Task res = client.PostAsync(url, content); ` for `System.Threading.Tasks.Task res = await client.PostAsync(url, content);`, or this short form`var res = client.PostAsync(url, content);` – Daniel Mar 14 '22 at 22:09
  • I've noticed that you are using System.Threading.Tasks.Task Try to use var like in my answer, it will give you more options to work with and not bind you to one type, plus, you should make the method async and await the the postAsync function call. – Liad Mar 15 '22 at 17:06

3 Answers3

1

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.

Liad
  • 336
  • 5
  • 15
  • 1
    I suppose I should replace act by object in your code, else where is act comming from ? – Antoine Pelletier Mar 14 '22 at 13:38
  • Yes, my bad, forgot to replace it. Hope it will work for you :) Btw, the variable "res" is used for debugging and observing what is wrong in the http request you have just sent. You could debug and see what is the problem with the http request. (Please update on your progress) – Liad Mar 14 '22 at 18:32
1

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);
}
MD. RAKIB HASAN
  • 3,670
  • 4
  • 22
  • 35
0

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.

Antoine Pelletier
  • 3,164
  • 3
  • 40
  • 62