C#一般处理程序

  一般处理程序:是一个实现System.Web.IHttpHandler接口的特殊类。任何一个实现了IHttpHandler接口的类,是作为一个外部请求的目标程序的前提。它由支持ASP.NET的服务器调用和启动运行。 一个HttpHandler程序负责处理它所对应的一个或一组URL地址的访问请求,并接收客户端发出的访问请求信息(请求报文)和产生响应内容(响应报文)。

创建方式:在web项目先添加新项---》web---->常规 ---》一般处理程序。创建一个一般处理程序将会生成两个后缀名的文件.ashx和.ashx.cs。shx里只有一个指令集,没有任何其他代码;ashx.cs就是页面处理代码。

HttpContext: 请求上下文对象,包含:请求报文对象(HttpRequest),响应报文对象(HttpResponse),服务器帮助类(Server),Session等。

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using DAL;
using System.Data;

namespace WebApplication1
{
/// <summary>
/// ListHandler 的摘要说明
/// </summary>
public class ListHandler : IHttpHandler
{
SQLHelper SQLHelper = new SQLHelper();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<html>" +
"<head></head>" +
"<body>" +
"<a href='AddPersonInfo.html'>添加</a><br/><br/>");

//拼接表头
sb.Append("<table>" +
"<tr>" +
"<th>ID</th>" +
"<th>NAME</th>" +
"<th>AGE</th>" +
"<th>操作</th>" +
"</tr>");

string strsql = "";
DataTable dt = SQLHelper.ExecuteAdapter(strsql,CommandType.Text);
if (dt.Rows.Count > 0)
{
int i = 0;
foreach(DataRow row in dt.Rows)
{

//拼接字符串(每行的数据)
sb.AppendFormat("<tr>" +
"<td>{0}</td>" +
"<td>{1}</td>" +
"<td>{2}</td>" +
"<td><a href='ShowDetail.ashx?id={0}'>详情</a></td>" +
"</tr>",
row.Table.Rows[i]["id"],
row.Table.Rows[i]["name"],
row.Table.Rows[i]["age"]
);

i++;
}
}
sb.Append("</table>");

      sb.Append("</body></html>");

context.Response.Write(sb.ToString());//将html写进来

}

public bool IsReusable
{
get
{
return false;
}
}
}
}

输出一个文件(比如图片):

context.Response.ContentType = "image/jpg";//相对路径的image文件夹下
context.Response.WriteFile("dlf.jpg");
原文地址:https://www.cnblogs.com/jiangyuhu/p/11966330.html