context.Response.ContentType = "text/html";返回的数据类型是html
使用字符串拼接的方式将数据库表的数据,拼接成一个html格式的字符串。
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
StringBuilder sb = new StringBuilder();
sb.Append("<html><head></head><body>");
sb.Append("<table><tr><th>ID</th><th>userName</th><th>passWord</th></tr>");
string str = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
string sql = "select top(10) Id, UserName, PassWord from t_users";
using(SqlConnection conn=new SqlConnection (str))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//拼接字符串,使用占位符填充数据
sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
reader.GetInt32(0),
reader.GetString(1),
reader["password"]);
}
}
}
sb.Append("</table>");
sb.Append("</body></html>");
context.Response.Write(sb.ToString());
}
网页加载数据成功。