Home > Net >  ASP.NET Web Forms: Make an external API Request and display response on page
ASP.NET Web Forms: Make an external API Request and display response on page

Time:12-14

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?

CodePudding user response:

Read the HttpClient's response with ReadAsStringAsync()

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

Please see HttpClient Class

CodePudding user response:

Just Use Ajax.

document.getElementById('livesearchtags').addEventListener('keyup', function (e) { //Run LiveSearch on ever key up LiveSearch() }); function LiveSearch() { //Get the input value let div = document.getElementById("sresult") div.style.display = "block"; let value = document.getElementById('livesearchtags').value $.ajax({ type: "POST", url: "sdata.aspx?Search=" value, //url: "sdata.aspx?Search=" & value, // Attach the value to a parameter called search data: { search: value }, datatype: "html", success: function (data) { // Insert the returned search results html into the result element $('#result').html(data); div.innerHTML = data; } }); }
  • Related