HttpHandler案例

1.访问者信息:

先新建名为 访问者信息.ashx的文件

<%@ WebHandler Language="C#" Class="访问者信息" %>

using System;
using System.Web;

public class 访问者信息 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
        using(System.Drawing.Bitmap bitmap=new System.Drawing.Bitmap(350,300))
        {
            using(System.Drawing.Graphics g=System.Drawing.Graphics.FromImage(bitmap))
            {
                g.DrawString("IP:"+context.Request.UserHostAddress,new System.Drawing.Font("宋体",30),System.Drawing.Brushes.Red,0,0);
                g.DrawString("操作系统:" + context.Request.Browser.Platform, new System.Drawing.Font("宋体", 30), System.Drawing.Brushes.Red, 0, 50);
                g.DrawString("浏览器版本:" + context.Request.Browser.Platform, new System.Drawing.Font("宋体", 30), System.Drawing.Brushes.Red, 0, 100);
            }
            bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


执行后结果为

 

 

 

 

 2.HttpHandler实现文件下载

      如果HttpHandler 输出的是html、txt、jpeg等类型的信息,那么浏览器会直接显示,如果希望弹出保存对话框,则需要添加 Header:string encodeFileName=HttpUtility.UrlEncode("XXX.txt");Response.AddHeader("Content-Disposition",string.Format("attachment;filename=\"{0}\"",encodeFileName));

其中filename 后为编码后的文件名。filename段为建议的保存文件名

 

先新建名为  Download.ashx文件

<%@ WebHandler Language="C#" Class="Download" %>

using System; using System.Web;

public class Download : IHttpHandler {         public void ProcessRequest (HttpContext context) {         context.Response.ContentType = "image/JPEG";         string filename=HttpUtility.UrlEncode("AAAA.jpg");//url编码,防止乱码         context.Response.AddHeader("Content-Disposition", "attachment;filename="+filename);         context.Response.WriteFile("AAAA.jpg");            }       public bool IsReusable {         get {             return false;         }     }

}


 

 

 

 

 

3.先解释下动态输出的用处:不用再把资源保存到磁盘上在输出(不会有文件重名的问题,文件不生成在服务器端。)

 

 

3.HttpHandler实现NPOI的相关操作

现在简单举个例子,

用NPOI动态生成一个Excel表然后弹出对话框让用户下载,文件名是“用户列表.xls”。

 

(一).先简单创建一个名为UserInfo的数据库,再新建个T_Users的表,有UserName,Password两个字段。然后填入一些数据

 

(二).分别创建名为DownloadExcel.aspx和DownloadExcel.ashx 两个文件。

再DownloadExcel.ashx中。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using System.Data.SqlClient;
using System.Data;

namespace NPOI_EXCEL_
{
    /// 
    /// DownloadExcel 的摘要说明
    /// 
    public class DownloadExcel : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            /*
            context.Response.ContentType = "application/x-excel";
            context.Response.ContentType = "application/x-excel";
            string filename = HttpUtility.UrlEncode("动态数据.xls");//文件名进行url编码,防止乱码
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.CreateSheet();
            HSSFRow row = sheet.CreateRow(0);
            HSSFCell cell1 = row.CreateCell(0);
            cell1.SetCellValue("hell0");
            row.CreateCell(1).SetCellValue(3.14);
            workbook.Write(context.Response.OutputStream);
             */
            context.Response.ContentType = "application/x-excel";
            context.Response.ContentType = "application/x-excel";
            string filename = HttpUtility.UrlEncode("用户列表.xls");//文件名进行url编码,防止乱码
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.CreateSheet();

            using (SqlConnection conn = new SqlConnection(@"Data Source=SGBCNQ6RQ6IMM9V;Initial Catalog=UserInfo;User ID=sa;Password=123456"))
            {
                conn.Open();
                using(IDbCommand cmd=conn.CreateCommand())
                {
                    cmd.CommandText = "select * from T_Users";
                    using(IDataReader reader=cmd.ExecuteReader())
                    {
                        int rownum = 0;
                        while (reader.Read())
                        {
                            string username=reader.GetString(reader.GetOrdinal("UserName"));
                            string password=reader.GetString(reader.GetOrdinal("Password"));
                            HSSFRow row = sheet.CreateRow(rownum);

                            row.CreateCell(0).SetCellValue(username);
                            row.CreateCell(1).SetCellValue(password);
                            rownum++;
                        }
                    }
                }    
            }
            workbook.Write(context.Response.OutputStream);
        }

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


 

关于NPOI的DLL可以上网找找,很容易找到。

 

然后再DownloadExcel.aspx中,代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DownloadExcel.aspx.cs" Inherits="NPOI_EXCEL_.DownloadExcel1" %>





    


    


 

 

 

执行的结果为:

 

然后数据库的数据就导入到了EXCEL中了

 

 

你可能感兴趣的:(HttpHandler案例)