第十一节 6HttpHandler案例

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
/* HttpHandler1
 * HttpHandler是对请求的响应,可以输出普通的html内容,也可以输出图片,也可以输出一个文件(下载)
 * 输出一幅动态创建的图片(能看懂就可以)
 * 
 * 案例1: 图片中显示的访问者信息
 * 案例2: 填入朋友的姓名就能生成恶搞的图片链接
 * 网上看到的注册,登陆时候的验证码也是动态生成的图片,55.la也是这样实现的原理
 *
 * 
 * HttpHandler实现文件下载
 * 如果HttpHandler输出的是html,txt, jpeg等类型的信息,那么浏览器会直接显示,如果希望弹出保存对话框,则需要添加
 * Header: string encodeFileName = HttpUtility.UrlEncode("过滤语.txt"); 
 * Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"",encodeFileName));
 * 其中filename后为编码后的文件名,filename段为建议的保存文件名
 * 
 * 动态输出用处,不用再把资原保存到磁盘上再输出(不会有文件重名的问题,文件不生成在服务器端)
 * 案例: 点周链接弹出图片下载对话框
 * 
 * 练习: 用NPOI动态生成一个Execel表然后弹出对话框让用户下载,文件名是"用户列表.xls"
 * 
 * 练习: 从数据库用户表导出数据到Excel文件,让用户下载, mdf放到App_Data下,asp.net不用那段设置DataDirectory的代码,用DataReader的方式读取数据
 * 
 * 练习: 用户表增加一个级别字段,只有登陆用户才能下载images下的图片文件(session中标识是否登录),如果用户没有登录则首先重定向到登录界面让用户登录,用户
 * 登录成功则跳转到下载列表页面,下载链接固定写好即可,如果登妹用户是普通用户则在图片左下解加上"免费用户试用"的字样
 * 练习: 给上面的程序加上登录验证码
 * 
 */
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string dataDir = AppDomain.CurrentDomain.BaseDirectory;
        if (dataDir.EndsWith(@"\bin\Debug\")
            || dataDir.EndsWith(@"\bin\Release\"))
        {
            dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
            AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
        }
    }


    /*
             using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\MyProjects\C#net传智播客\第十一节asp.net中级\导出Excel\App_Data\Database.mdf;Integrated Security=True;User Instance=True"))
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand()) 
            {
                cmd.CommandText = "select * FROM T_User";
                using(SqlDataReader reader = cmd.ExecuteReader())
                {
                    HSSFRow _row = sheet.CreateRow(0);
                    _row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("ID");
                    _row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("用户名");
                    _row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue("性别");
                    int rownum = 1;
                    while (reader.Read()) 
                    {
                        Int64 id = reader.GetInt64(reader.GetOrdinal("id"));
                        string name = reader.GetString(reader.GetOrdinal("name"));
                        string sex = reader.GetString(reader.GetOrdinal("sex"));
                        HSSFRow row = sheet.CreateRow(rownum);
                        row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(id);
                        row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue(name);
                        row.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue(sex);


                        rownum++;
                        //context.Response.Write("id:"+id+", name:"+name+", sex="+sex+"<BR>");
                    }
                }
            }
        }        
     */
}

  

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

using System;
using System.Web;

public class HttpHandler1 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
        //context.Response.Write("Hello World");
        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(300, 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, 100);
                g.DrawString("浏览器:" + context.Request.Browser.Type, new System.Drawing.Font("宋体", 30), System.Drawing.Brushes.Red, 0, 150);
            }
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

  

<%@ WebHandler Language="C#" Class="HttpHandler2" Debug=true %>

using System;
using System.Web;

public class HttpHandler2 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
        string name = context.Request["name"];
        string imgfile = HttpContext.Current.Server.MapPath("3.jpg");
        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(imgfile)) 
        {
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) 
            {
                g.DrawString(name, new System.Drawing.Font("宋体",30), System.Drawing.Brushes.Red, 50,50);
            }
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="xiazan.aspx.cs" Inherits="xiazan" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
   
   <a href="1.jpg">图片1</a>
   <a href="1.txt">txt</a>
   <a href="1.jpg">图片3</a>


   <a href="xiazan.ashx">图片4</a>

</body>
</html>

  

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

using System;
using System.Web;

public class xiazan : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
        //context.Response.Write("Hello World");
        //这里如果用中文文件名的话,有可能出现乱码
        //context.Response.AddHeader("Content-Disposition", "attachment;filename=呵呵.jpg");

        context.Response.AddHeader("Content-Disposition", HttpUtility.UrlEncode("attachment;filename=哥哥哥哥.jpg"));
        
        context.Response.WriteFile("3.jpg");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

  

posted @ 2012-03-19 23:10  简单--生活  阅读(347)  评论(0编辑  收藏  举报
简单--生活(CSDN)