简体   繁体   中英

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

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?

Read the HttpClient's response with ReadAsStringAsync()

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

Please see HttpClient Class

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM