Send (Pass) JSON to API URL with POST Method in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

Dear Sir

How to send this JSON format from Server Side with POST method to a URL .

> CANo will be a Textbox Text.

> DLimit will be a Textbox Text

{
    "loginId": "CK20004098",
    "cardList" : [{ 
        "caNo": "0054723860",
        "dLimit": "10.00",
        "adhoc": 0.00,
        "mLimit": 0.00,
        "limitType": "1"
    }]
}

 

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi Amitabha,

For passing the json you need to create a class object and set the value and Serialize to json string and pass to the url.

For more details refer below sample code.

Model

public class JsonModel
{
    public string loginId { get; set; }
    public List<CardList> cardList { get; set; }
}

public class CardList
{
    public Int32 caNo { get; set; }
    public decimal dLimit { get; set; }
    public decimal adhoc { get; set; }
    public decimal mLimit { get; set; }
    public string limitType { get; set; }
}

Controller

public class CardAPIController : ApiController
{
    [Route("api/CardAPI/GetCards")]
    [HttpPost]
    public JsonModel GetCards(JsonModel model)
    {
        return model;
    }
}

Calling the API in Page

Namespaces

using System.Net;
using System.Text;
using System.Web.Script.Serialization;

Code

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string apiUrl = "http://localhost:26404/api/CardAPI";

        JsonInput input = new JsonInput();
        input.loginId = "CK20004098";
        List<CardList> cardList = new List<CardList>();
        // Set the value from controls.
        cardList.Add(new CardList
        {
            caNo = 0054723860,
            dLimit = 10.00M,
            adhoc = 0.00M,
            mLimit = 0.00M,
            limitType = "1"
        });
        input.cardList = cardList;

        string inputJson = (new JavaScriptSerializer()).Serialize(input);
        WebClient client = new WebClient();
        client.Headers["Content-type"] = "application/json";
        client.Encoding = Encoding.UTF8;
        string json = client.UploadString(apiUrl + "/GetCards", inputJson);
    }
}

public class JsonInput
{
    public string loginId { get; set; }
    public List<CardList> cardList { get; set; }
}

public class CardList
{
    public Int32 caNo { get; set; }
    public decimal dLimit { get; set; }
    public decimal adhoc { get; set; }
    public decimal mLimit { get; set; }
    public string limitType { get; set; }
}