HttpHandle之温故知新

本例通过httphandle在页面上画矩形色条来演示HttpHandle用法

类库代码:

using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace ClassLibrary1
{
    public class Class1:IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string c = context.Request["c"];
            string cr = context.Request["r"];
            string cg = context.Request["g"];
            string cb = context.Request["b"];
            if (!string.IsNullOrEmpty(c))
            {
                int ir = 200;
                int ig = 200;
                int ib = 200;
                int count = 0;
                int.TryParse(cr, out ir);
                int.TryParse(cg, out ig);
                int.TryParse(cb, out ib);
                int.TryParse(c,out count);

                Color cc = Color.FromArgb(ir, ig, ib);
                Bitmap b = new Bitmap(count, 20);
                Graphics g = Graphics.FromImage(b);
                MemoryStream m = new MemoryStream();
                SolidBrush sb = new SolidBrush(cc);
                try
                {
                    g.FillRectangle(sb, 0, 0, count, 20);
                    b.Save(m, ImageFormat.Png);
                    context.Response.ContentType = "image/png";
                    context.Response.OutputStream.Write(m.ToArray(), 0, (int)m.Length);
                }
                catch
                {
                    m.Close();
                    sb.Dispose();
                    sb = null;
                    g.Dispose();
                    g = null;
                }
            }
        }

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

web.config关键配置,加在system.web中任何地方都行

<httpHandlers>
        <add verb="*" path="img.xy" type="ClassLibrary1.Class1,ClassLibrary1"/>
      </httpHandlers>

显示页面default.aspx代码
<table width="70%" border="1">
        <tr>
            <td>标题</td>
            <td>标识</td>
        </tr>
        <tr>
            <td>实现动态生成图片</td>
            <td><img src="img.xy?c=100" /></td>
        </tr>
        <tr>
            <td>实现动态</td>
            <td><img src="img.xy?c=50&r=<%=Request["r"] %>&g=<%=Request["g"] %>&b=<%=Request["b"] %>" /></td>
        </tr>
    </table>
上面一个带了参数,一个没带参数

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值