[英]ASP.NET Web Forms: Make an external API Request and display response on page
我發現了很多關於 ASP.NET Web API 的帖子,但沒有找到經典 Web Forms 的帖子。我想調用外部 API 並將其結果顯示在 883658850 文本字段上。 但是即使 API 調用成功,也沒有收到響應(或者至少沒有在頁面上顯示。
C# 后面的代碼:
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 頁:
<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>
我應該怎么做? 我應該將 UpdatePanel 添加到我的 ASP.NET 頁面嗎?
使用ReadAsStringAsync()讀取 HttpClient 的響應
string responseBody = await response.Content.ReadAsStringAsync();
由於 Optimize 方法是異步的,請嘗試像這樣更改代碼。
//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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.