skip to Main Content

I’ve found a lot of posts for ASP.NET Web API but nothing at all for classic Web Forms. I want to call an external API and display its result on a web page text field. But even though the API call is successful, the response is not received (or at least not shown on the page.

C# code behind:

protected void btnOptimize_Click(object sender, EventArgs e) {
  Optimize();
}

public async Task Optimize() {
  string URI = "https://EXTERNAL_API_BASE_URL/POST";
  string auth = "Bearer XXXX";

  var client = new HttpClient();

  MyData data = new MyData();
  data.text = "Hello world";

  string requestBody = JsonConvert.SerializeObject(data);

  var stringContent = new StringContent(requestBody);

  client.DefaultRequestHeaders.Add("Content-Type", "application/json");
  client.DefaultRequestHeaders.Add("Authorization", auth);

  var response = await client.PostAsync(URI, stringContent);

  //display on page's text field
  txtResponse.Value = response.Content.ToString();
}

ASP.NET Page:

<body>
    <form id="form1" runat="server">
        <div>
            <textarea runat="server" id="txtInput"></textarea>
            <asp:Button ID="btnOptimize" runat="server" OnClick="btnOptimize_Click" Text="Generate" />
            <textarea runat="server" id="txtResponse"></textarea>
        </div>
    </form>
</body>

What should I do differently? Should I add an UpdatePanel to my ASP.NET page?

2

Answers


  1. Read the HttpClient’s response with ReadAsStringAsync()

    string responseBody = await response.Content.ReadAsStringAsync();
    

    Please see HttpClient Class

    Login or Signup to reply.
  2. Since the Optimize method is async, try changing the code like this.

    //First change the method so it's async as well.
    protected async Task btnOptimize_Click(object sender, EventArgs e) {
      //Then call the Optimize() method using the await keyword.
      await Optimize();
    }
    
    public async Task Optimize() {
      string URI = "https://EXTERNAL_API_BASE_URL/POST";
      string auth = "Bearer XXXX";
    
      var client = new HttpClient();
    
      MyData data = new MyData();
      data.text = "Hello world";
    
      string requestBody = JsonConvert.SerializeObject(data);
    
      var stringContent = new StringContent(requestBody);
    
      client.DefaultRequestHeaders.Add("Content-Type", "application/json");
      client.DefaultRequestHeaders.Add("Authorization", auth);
    
      var response = await client.PostAsync(URI, stringContent);
    
      //display on the page's text field
      //You should get value using the await keyword.
      //response.content also has a method called ReadAsStringAsync(),
      //it should be visible if you are using intellisense in VisualStudio
      txtResponse.Value = await response.Content.ReadAsStringAsync();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search