這篇文章主要是對ashx文件的使用進行了介紹。需要的朋友可以過來參考下,希望對大家有所幫助
一提到Ashx文件,我們就會想到http handler以及圖片加載(在之前我們一般使用ASPX或者Webservice去做),一般做法如下: Handler.ashx: 代碼如下: <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.IO; using System.Web; public class Handler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest (HttpContext context) { context.Response.ContentType = "image/jpeg"; context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.BufferOutput = false; PhotoSize size; switch (context.Request.QueryString["Size"]) { case "S": size = PhotoSize.Small; break; case "M": size = PhotoSize.Medium; break; case "L": size = PhotoSize.Large; break; default: size = PhotoSize.Original; break; } Int32 id = -1; Stream stream = null; if (context.Request.QueryString["PhotoID"] != null && context.Request.QueryString["PhotoID"] != "") { id = Convert.ToInt32(context.Request.QueryString["PhotoID"]); stream = PhotoManager.GetPhoto(id, size); } else { id = Convert.ToInt32(context.Request.QueryString["AlbumID"]); stream = PhotoManager.GetFirstPhoto(id, size); } if (stream == null) stream = PhotoManager.GetPhoto(size); const int buffersize = 1024 * 16; byte[] buffer = new byte[buffersize]; int count = stream.Read(buffer, 0, buffersize); while (count > 0) { context.Response.OutputStream.Write(buffer, 0, count); count = stream.Read(buffer, 0, buffersize); } } } *.aspx: <img src="myHttpHander.ashx?id=123" width="20" height="20" /> 我們變通以下,發現其實除了可以輸出圖片以外,還可以輸出文字: Handler.ashx: 代碼如下: <%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("alert('hi')"); } public bool IsReusable { get { return false; } } } *.aspx: 彈出alert <script src="Handler.ashx"></script> 也可以把.ashx當成css文件 <link href="css/Handler.ashx" rel="stylesheet" type="text/css"> xml文件 orderDoc.load("Handler.ashx"); 還可以嵌入文字: Handler.ashx: 代碼如下: <%@ WebHandler Language="C#" Class="TestHandler" %> using System; using System.Web; public class TestHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("document.write("Hello World");"); } public bool IsReusable { get { return false; } } } *.aspx: <script type="text/javascript" src="TestHandler.ashx" /> 當你希望從ashx或HttpHandler裡訪問你的Session時,你必須實現IReadOnlySessionState接口. 代碼: 代碼如下: using System; using System.Web; using System.Web.SessionState; public class DownloadHandler : IHttpHandler, IReadOnlySessionState { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext ctx) { ctx.Response.Write(ctx.Session["fred"]); } } 其實,學習的思路不應該這樣,以上除了圖片外,我們都用偏了,為什麼用偏了呢,因為軟件以簡單、實用為主,我們只是把以上純粹看成可一項技術而沒有把它放到軟件的地位去考慮:) 具體的用途,大家可以參考Rewirte.dll (這個dll,可以使服務器支持偽靜態的)