1、演示界面
使用asp自带的组件 ScriptManager和UpdatePanel实现异步请求和异步刷新

2、程序
cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace demo1
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//异步
protected void Button1_Click(object sender, EventArgs e)
{
HttpGetAsync();
}
//get同步
public void HttpGet()
{
string url = "http://dev.witersen.com/api.php?function=Async"; //本人测试接口
Dictionary<string, string> headers = new Dictionary<String, string>();
headers.Add("cookie", ""); //示例
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = client.GetAsync(url).Result;
string result = response.Content.ReadAsStringAsync().Result;
TextBox2.Text = result;
}
}
//同步
protected void Button2_Click(object sender, EventArgs e)
{
HttpGet();
}
//get异步
public async void HttpGetAsync()
{
string url = "http://dev.witersen.com/api.php?function=Async"; //本人测试接口
Dictionary<string, string> headers = new Dictionary<String, string>();
headers.Add("cookie", ""); //示例
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = await client.GetAsync(url);
string result = await response.Content.ReadAsStringAsync();
TextBox1.Text = result;
}
}
}
}
aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="demo1.index" Async="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="异步调用" />
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="129px" TextMode="MultiLine" Width="119px"></asp:TextBox>
<br />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="同步调用" />
<br />
<asp:TextBox ID="TextBox2" runat="server" Height="129px" TextMode="MultiLine" Width="119px"></asp:TextBox>
<br />
<br />
---------------说明---------------<br />
请求的接口为本人接口:<a href="http://dev.witersen.com/api.php">http://dev.witersen.com/api.php</a><br />
请求测试方法:async<br />
方法中会sleep 3s</div>
</form>
</body>
</html>
原创文章,作者:witersen,如若转载,请注明出处:https://www.witersen.com