asp.net項目中,使用.ashx的文件(通常處理程序)能夠用於處理客戶端發送來的請求,並將服務器端的處理結果返回給客戶端。它能返回的類型能夠是文本、或者圖片。有時候,咱們能夠在項目中使用.cs的文件來幹一樣的活。可是,直接在瀏覽器上訪問.cs的文件是會被無情的拒絕的。這時候須要在Web.Config中進行配置一下就OK了。javascript
開始寫這篇博客前,翻閱了其餘資料。發現這個知識點遠不是我如今所能寫的清楚的。但我想,學習總得有個過程,既然在過程當中我知道了這一點,那就記錄下來。等到有更深刻的瞭解之後,再去記錄那更深層的東西吧。另外,本文中用到的驗證碼生成的例子,參考Insus.Net博友的一篇博客(Insus.Net),在此表示感謝,閱讀他的博客學習到很多知識。html
首先在項目中建立一個.ashx結尾的通常處理程序(CreateVerifyCodeHandler.ashx)和一個.cs結尾的類文件(CreateVerifyCode.cs)。再建立一個Html文件,用於展現驗證碼。Refresh的腳本函數放在RealTime.js腳本文件中,用於刷新驗證碼圖片。html代碼以下:java
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="js/jquery-2.0.3.min.js"></script> <script type="text/javascript" src="js/RealTime.js"></script> </head> <body> <p>從.ashx文件中獲取驗證碼</p> <img id="ashxValidateCodeImg" src="/Handlers/CreateVerifyCodeHandler.ashx" onclick="Refresh('ashxValidateCodeImg')" /> <hr /> <p>從.cs文件中獲取驗證碼</p> <img id="csValidateCodeImg" src="/Handlers/CreateVerifyCode.ashx" onclick="Refresh('csValidateCodeImg')" /> </body> </html>
再看看CreateVerifyCodeHandler.ashx的代碼。jquery
public class CreateVerifyCodeHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.Clear(); using (Bitmap b = new Bitmap(150, 40, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(b)) { Rectangle rect = new Rectangle(0, 0, 148, 38); g.FillRectangle(Brushes.White, rect); string drawString = RandomCharacters.GenerateRandomString(8); Font drawFont = new Font("Arial", 16, FontStyle.Italic | FontStyle.Strikeout); using (SolidBrush drawBrush = new SolidBrush(Color.Black)) { PointF drawPoint = new PointF(15, 10); g.DrawRectangle(new Pen(Color.Red, 0), rect); g.DrawString(drawString, drawFont, drawBrush, drawPoint); } b.Save(context.Response.OutputStream, ImageFormat.Jpeg); context.Response.ContentType = "image/jpeg"; context.Response.End(); } } } public bool IsReusable { get { return false; } } }
此時,咱們能夠在瀏覽器上直接打開瀏覽該通常處理程序,由於其返回的是一個圖片文件。如圖:web
打開CreateVerifyCodeHandler.ashx文件,發現裏面的代碼和普通的類程序裏面的代碼沒什麼區別。那能不能用一個普通的類文件去幹一樣的事情呢?因此,咱們把代碼複製到CreateVerifyCode.cs文件中。以一樣的方式,在瀏覽器中嘗試瀏覽這個.cs文件,看到的結果確實像下面這樣。瀏覽器
接下來,打開web.config文件,找到<httpHandler>節,添加下面的配置。服務器
<add verb="*" path="CreateVerifyCode.ashx" type="WebApplication1.Handlers.CreateVerifyCode" validate="false"/>
再次瀏覽CreateVerifyCode文件,但這個時候須要注意了,咱們須要將文件名改成CreateVerifyCode.ashx去訪問。不然沒法直接瀏覽.cs結尾的文件。至此,咱們也能夠直接在瀏覽器上查看最初建立的Html文件,點擊圖片也可以刷新驗證碼了。asp.net