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

网页加载数据成功。
这篇博客介绍了如何使用ASP.NET的一般处理程序(HTTP Handler)来生成HTML内容。通过设置Response.ContentType为"text/html",然后利用StringBuilder拼接SQL查询到的数据库表数据,转化为HTML表格格式。代码示例展示了如何打开数据库连接,执行SQL查询,读取数据并逐行填充到HTML表格中,最后将生成的HTML字符串写入响应。

被折叠的 条评论
为什么被折叠?



