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
Read the HttpClient’s response with ReadAsStringAsync()
Please see HttpClient Class
Since the Optimize method is async, try changing the code like this.