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");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM