locked
POST from client is not working RRS feed

  • Question

  • User1751268424 posted

    Hi,

    I'm trying to POST to my WebAPI server unsuccessfully. What is wrong with this code? I've tested this Web API using Postman am,d it's ok. Here is my code.

                    // Send Fire Event to PMK
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri("http://192.168.151.100:8080/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    
                    var serialize = JsonConvert.SerializeObject(fireEvent);
                    var response = await client.PostAsync("api/FireEvents", 
                        new StringContent(serialize, Encoding.Unicode, "application/json"));

    Thank you soo much

    Jannen

    Thursday, August 18, 2016 8:33 PM

Answers

  • User1751268424 posted

    Hi all,

    Thanks for replies.

    It was my IIS setting incorrectly. I did not set ASP.NET 4.6.

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 20, 2016 8:30 PM

All replies

  • User36583972 posted

    Hi jsiahaan,

    You can refer the following code.

    HttpClient:

                using (var client = new System.Net.Http.HttpClient())
                {
                    // HTTP POST
                    var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
                    client.BaseAddress = new Uri(baseUrl);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
      
                    var content = new StringContent(JsonConvert.SerializeObject("Test"), Encoding.UTF8, "application/json");
                    var response = client.PostAsync("/api/Values", content).Result;
                    string s = await response.Content.ReadAsStringAsync();
                }

    Best Regards,

    Yohann Lu

    Friday, August 19, 2016 2:01 AM
  • User1751268424 posted

    Hi all,

    Thanks for replies.

    It was my IIS setting incorrectly. I did not set ASP.NET 4.6.

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 20, 2016 8:30 PM