Web Forms aspx - PostAsync Web API

30 Views Asked by At
  1. I have a Web Forms application calling a Web API post action but it is not working.
  2. Calling the Post action from Swagger and Postman is working. So am thinking the issue is not in the Web API.
  3. Have tried using the PostAsJsonAsync function but the outcome is the same.
  4. The execution hangs at the line "HttpResponseMessage response = await client.PostAsync("api/create", RawText);"
  5. Kindly assist

Web Forms Method

        public async Task<CSSetup> CSCreateSetup(CSAudit TempAudit)
        {
            using (var client = new HttpClient())
            {
                var APIPath = Session["APIPath"].ToString();
                CSSetup TempSetup = new CSSetup();

                //Content
                var json = JsonConvert.SerializeObject(TempAudit);
                var RawText = new StringContent(json, UnicodeEncoding.UTF8, "application/json");

                //HttpClient
                client.BaseAddress = new Uri(APIPath);
                HttpResponseMessage response = await client.PostAsync("api/create", RawText);
                if (response.IsSuccessStatusCode)
                {
                    TempSetup = await response.Content.ReadAsAsync<CSSetup>();
                }
                else
                {
                    Session["Message"] = "Error creating setup";
                }

                return await Task.FromResult(TempSetup);
            }
        }

Post Action

        [HttpPost]
        [Route("Create")]
        public async Task<ActionResult> CreateSetup(CSAudit TempAudit)
        {
            try
            {
                return Ok(await setupManager.CSCreateSetup(TempAudit));
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError,  "Error creating setup object");
            }
        }

Calling CreateSetup

        protected async void BtnSave_Click(object sender, EventArgs e)
        {
            var TempAudit = new CSAudit("ADMIN", DateTime.Now.ToString("yyyyMMdd"));
            CSSetup TempSetup = (CSCreateSetup(TempAudit)).Result;
        }

What I have tried

  1. Created the Web API Post action and the Web Form method to consume the Post action
  2. I was expecting the Web Forms data to Post the data supplied and return the expected data
2

There are 2 best solutions below

6
Eli Kihara On

I have converted the call to include Result and removed the await. Have also removed the async key word from the CreateSetup method.

Old Code

HttpResponseMessage response = await client.PostAsync("api/create", RawText);

New Code

HttpResponseMessage response = client.PostAsync("api/create", RawText).Result;
1
Eli Kihara On

Have changed the CreateSetup Method to below. Hope it helps someone else

    public CSSetup CSCreateSetup(CSAudit TempAudit)
    {
        //Global
        var APIPath = Session["APIPath"].ToString();
        var uri = APIPath + "/api/setup/create";
        CSSetup TempSetup = new CSSetup();

        //Content 
        string json = JsonConvert.SerializeObject(TempAudit);

        // Create a request object
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = json.Length;

        // Write the JSON data to the request stream
        using (Stream dataStream = request.GetRequestStream())
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(json);
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        // Get the response from the server
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream dataStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(dataStream);
                string responseString = reader.ReadToEnd();
                TempSetup = JsonConvert.DeserializeObject<CSSetup>(responseString);
            }
        }

        return TempSetup;
    }