3

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.

asked Jun 26, 2017 at 14:49
7
  • Debug the application and check what string content you are really posting. Compare it with the one you had to post Commented Jun 26, 2017 at 14:54
  • 3
    Why are you mixing HttpWebRequest and HttpClient? Commented Jun 26, 2017 at 14:55
  • @mason OP is also creating an obsolete serializer instance. Maybe some kind of throttle ;o) Commented Jun 26, 2017 at 14:56
  • 1
    Is there a reason why you initialize JavaScriptSerializer serializer but never use it? Commented Jun 26, 2017 at 14:56
  • 2
    You are creating an HttpWebRequest and then doing nothing with it. Then you're posting data using an HttpClient. You need to pick one or the other, don't mix them, and don't create a request and then not send it Commented Jun 26, 2017 at 14:57

2 Answers 2

5

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;
 }
answered Jun 30, 2017 at 14:22
1

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);
 }
answered Jun 27, 2017 at 15:22
1
  • I wasn't able to comment below. It is not a good idea to put too much inside the catch block. What if there is another exception inside it? Commented Jun 30, 2017 at 19:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.