欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET笔记之 Httphandler的操作详解

程序员文章站 2024-03-03 18:38:10
1、httphandler          实例1:通过生成一张动态图片输出客户端的ip地址、操作系统类型、浏览器类...

1、httphandler

        ASP.NET笔记之 Httphandler的操作详解

实例1:通过生成一张动态图片输出客户端的ip地址、操作系统类型、浏览器类型

复制代码 代码如下:

<%@ webhandler language="c#" class="visitor" %>

using system;
using system.web;

public class visitor : ihttphandler {

    public void processrequest(httpcontext context)
    {
        context.response.contenttype = "image/jpeg";
        using (system.drawing.bitmap bitimage = new system.drawing.bitmap(330, 300))
        {
            //设置画布
            using (system.drawing.graphics g = system.drawing.graphics.fromimage(bitimage))
            {
                //ip
                g.drawstring("ip:" + context.request.userhostaddress, new system.drawing.font("宋体", 20), system.drawing.brushes.red, new system.drawing.pointf(0, 0));
                //操作系统
                g.drawstring("操作系统:" + context.request.browser.platform, new system.drawing.font("宋体", 20), system.drawing.brushes.red, new system.drawing.pointf(0, 50));
                //浏览器
                g.drawstring("浏览器:" + context.request.browser.type, new system.drawing.font("宋体", 20), system.drawing.brushes.red, new system.drawing.pointf(0, 100));
            }
            //保存到输出流中
            bitimage.save(context.response.outputstream, system.drawing.imaging.imageformat.jpeg);

        }
    }

    public bool isreusable {
        get {
            return false;
        }
    }

}


实例2:通过“下载”连接,弹出用户附件保存

html代码:<a href="dowload.ashx">下载</a>

复制代码 代码如下:

<%@ webhandler language="c#" class="dowload" %>

using system;
using system.web;

public class dowload : ihttphandler {

    public void processrequest(httpcontext context)
    {
        string filename = httputility.urlencode("悲剧.jpg");
        context.response.contenttype = "image/jpeg";

        //打开附件对话框  报文头header和设置它的值
        context.response.addheader("content-disposition", "attachment:filename=" + filename);
        context.response.writefile("苹果.jpg");      
    }

    public bool isreusable {
        get {
            return false;
        }
    }

}