在ashx文件中读写session
1
<%@ WebHandler Language="C#" Class="codeImage" %>2

3
using System;4
using System.Web;5
using System.Web.SessionState;6
using System.Web.UI;7
using System.Drawing;8
using System.Drawing.Imaging;9

public class codeImage :IHttpHandler,IRequiresSessionState
{10
11

public void ProcessRequest (HttpContext context)
{12
context.Response.ContentType = "text/plain";13
DrawImage(Getcodes(4),context);14
}15
16
17

public bool IsReusable
{18

get
{19
return false;20
}21
}22
public string[] Getcodes(int num)23

{24
string[] codes = new string[num];25

string[] str = new string[]
{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };26
Random rd = new Random();27
for (int i = 0; i < num; i++)28

{29
codes[i] = str[rd.Next(0, str.Length)];30
}31
return codes;32
}33
public string DrawImage(string[] codes,HttpContext context)34

{35

36
//定义图片大小37
Bitmap img = new Bitmap(50, 18);38
Graphics g = Graphics.FromImage(img);39
//刷子,字体40
Brush brush = new SolidBrush(Color.Wheat);41
Font f = new Font("Georgia", 8f, FontStyle.Bold);42
//在图片上填充距形43
g.FillRectangle(brush, 0, 0, 50, 18);44
Brush abrush = new SolidBrush(Color.Red);45
Brush bbrush = new SolidBrush(Color.Blue);46
for (int j = 0; j < codes.Length; j++)47

{48
SizeF sf = g.MeasureString(codes[j], f);49
if (j % 2 == 0)50

{51
g.DrawString(codes[j].ToString(), f, abrush, 3 + j * sf.Width, 1);52
}53
else54

{55
g.DrawString(codes[j].ToString(), f, bbrush, 3 + j * sf.Width, 1);56
}57

58
}59
string strcodes = "";60
for (int i = 0; i < codes.Length; i++)61

{62
strcodes += codes[i].ToString();63
}64
65
//HttpContext.Current.Session["code"] = strcodes;66
context.Session["code"] = strcodes;67
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);68
g.Dispose();69
img.Dispose();70
return strcodes;71
}72

73
}
这里和大家分享和学习如何学IT!

浙公网安备 33010602011771号