Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post JSON data to web API using object in C#

I was able to write the code to perform GET operation from a web API. But, I'm not able to POST. I think the problem is with the JSON object. I'm able to POST if the parameters are sent via URL but I'm unable to do so if it's a JSON Object. Eg: The POST requires me to send ModelID, CustomerID via URL and ReferenceString as a JSON object.

Data to POST

ModelID = 3345

CustomerID =1V34858493

ReferenceID is a JSON string[]

[ { "ReferenceId": "a123" } ]

Main

 static void Main(string[] args) 
    {
       // JavaScriptSerializer serializer = new JavaScriptSerializer();

        string patientServiceResponse = PostRequest( string.Format("https://url.com/api/{0}/{1}/taskOrders", 3345, "1V34858493"));

        Debug.Write(patientServiceResponse);
    }

POST Request

private static string PostRequest(string url)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json; charset=utf-8";
        string sContentType = "application/json";

        JObject oJsonObject = new JObject();

        oJsonObject.Add("ReferenceId", "a123");

        HttpClient oHttpClient = new HttpClient();
        var oTaskPostAsync = oHttpClient.PostAsync(url, new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType));

        //return 
    }

Can you please correct me where I'm going wrong.

like image 492
shockwave Avatar asked Sep 20 '26 23:09

shockwave


2 Answers

Thanks to Mason! I wrote the code to POST the data to the web API using HttpWebRequest.

Main

static void Main(string[] args) 
{
    string patientServiceResponse = PostRequest( string.Format("https://url.com/api/{0}/{1}/taskOrders", 3345, "1V34858493"));

    Debug.Write(patientServiceResponse);
}

POST

private static string PostRequest(string url)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "[  { \"ReferenceId\": \"a123\"  } ]";
            Debug.Write(json);
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
        try
        {
            using (var response = httpWebRequest.GetResponse() as HttpWebResponse)
            {
                if (httpWebRequest.HaveResponse && response != null)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException e)
        {
            if (e.Response != null)
            {
                using (var errorResponse = (HttpWebResponse)e.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        string error = reader.ReadToEnd();
                        result = error;
                    }
                }

            }
        }

        return result;

    }
like image 162
shockwave Avatar answered Sep 22 '26 11:09

shockwave


POST function will look like this.

    [HttpPost]
    [Route("{modelId}/{customerId}")]
    public IHttpActionResult Add(string modelId, string customerId, REFDto referenceId)
    {
        return Ok();
    }

Create a DTO class for reference Id

public class REFDto
{
    public string referenceId { get; set; }
}

API Client call :

        using (var client = new HttpClient())
        {
            var modelId = "3345";
            var customerId = "1V34858493";
            var url = $"https://url.com/api/{modelId}/{customerId}/taskOrders";
            JObject oJsonObject = new JObject();
            oJsonObject.Add("referenceId", "ref123");
            var response = await client.PostAsync(url, new StringContent(oJsonObject.ToString(), Encoding.UTF8, "application/json"));
            Console.WriteLine(response);
        }
like image 36
William Han Avatar answered Sep 22 '26 12:09

William Han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!