|
源代码网推荐大概去年九月的时候,做一个功能就是生成图片,当然有很多方法,生成图片放在服务器的某个目录下面,隔一段时间就删除,图还得自己画,嫌麻烦,结果找着这样一段代码,今天看到使用.ashx文件处理IHttpHandler实现发送文本及二进制数据的方法。突然发现这种用法讨论的很好,也许是没怎么详细介绍它的官方中文文档吧,并且推荐另外一种方法代替。 //---------------------------------------- //Pickyourfavoriteimageformat //------------------------------ byte[]byteArr=(byte[])oChartSpace.GetPicture("png",500,500); //---------------------------------------- //StorethechartimageinSessiontobepickedupbyanHttpHandlerlater //--------------------------------------- HttpContextctx=HttpContext.Current; stringchartID=Guid.NewGuid().ToString(); 源代码网整理以下ctx.Session[chartID]=byteArr; imgHondaLineup.ImageUrl=string.Concat("chart.ashx?",chartID); chart.ashx里面就下面一句话 <%@WebHandlerlanguage="C#"class="AspNetResources.Owc.ChartHandler"codebehind="chart.ashx.cs"%> 其实也可以用这个代替 在web.config里面的<system.web>里面加上 <httpHandlers> <addverb="*"path="*.ashx"type="AspNetResources.Owc,ChartHandler"validate="false"/>/*ChartHandler是那个ashx.cs编译后生成的代码Assembly*/ 源代码网整理以下<!--Sincewearegrabbingallrequestsafterthis,makesureError.aspxdoesnotrelyon.Text--> <addverb="*"path="Error.aspx"type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers> 具体使用哪个都无所谓,后一种配置好了就方便一些,不用管路径了,其实这个思想的应用比较知名的在.text里面就已经有了,只不过应用的方向不同。 ashx.cs文件的代码 usingSystem; usingSystem.Web.SessionState; usingSystem.IO; usingSystem.Web; namespaceAspNetResources.Owc { publicclassChartHandler:IHttpHandler,IReadOnlySessionState { publicboolIsReusable { get{returntrue;} } 源代码网整理以下publicvoidProcessRequest(HttpContextctx) { stringchartID=ctx.Request.QueryString[0]; Arrayarr=(Array)ctx.Session[chartID]; ctx.ClearError(); ctx.Response.Expires=0; ctx.Response.Buffer=true; ctx.Response.Clear(); MemoryStreammemStream=newMemoryStream((byte[])arr); memStream.WriteTo(ctx.Response.OutputStream); memStream.Close(); ctx.Response.ContentType="image/png"; ctx.Response.StatusCode=200; ctx.Response.End(); } } } 源代码网供稿. |