Around September last year, I was working on a function to generate pictures. Of course, there are many methods. The generated pictures were placed in a certain directory on the server and deleted after a period of time. I had to draw the pictures myself, which was too troublesome, but I found this paragraph. Code, today I saw how to use .ashx file to process IHttpHandler to implement sending text and binary data. Suddenly I found that this usage was well discussed. Perhaps the official Chinese document did not introduce it in detail, and recommended another method instead.
//----------------------------------------
//Pick your favorite image format
//--------------------------------
byte[] byteArr = (byte[]) oChartSpace.GetPicture ("png", 500, 500);
//----------------------------------------
// Store the chart image in Session to be picked up by an HttpHandler later
//------------------------------------------
HttpContext ctx = HttpContext.Current;
string chartID = Guid.NewGuid ().ToString ();
ctx.Session [chartID] = byteArr;
imgHondaLineup.ImageUrl = string.Concat ("chart.ashx?", chartID);
There is the following sentence in chart.ashx
<% @ WebHandler language="C#" class="AspNetResources.Owc.ChartHandler" codebehind="chart.ashx .cs" %>
In fact, you can also use this instead of
adding<httpHandlers>
to <system.web> in web.config
<add verb="*" path="*.ashx" type="AspNetResources.Owc, ChartHandler " validate="false" /> /*ChartHandler is the code Assembly generated after ashx.cs is compiled*/
<!--Since we are grabbing all requests after this, make sure Error.aspx does not rely on .Text -->
<add verb="*" path="Error.aspx" type="System.Web.UI.PageHandlerFactory" />
</httpHandlers>
It doesn’t matter which one you use. The latter one is more convenient once configured, no matter the path. In fact, the application of this idea is well-known in .text, but the application direction is different.
The code of ashx.cs file
using System;
using System.Web.SessionState;
using System.IO;
using System.Web;
namespace AspNetResources.Owc
{
public class ChartHandler : IHttpHandler, IReadOnlySessionState
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest (HttpContext ctx)
{
string chartID = ctx.Request.QueryString[0];
Array arr = (Array) ctx.Session [chartID];
ctx.ClearError ();
ctx.Response.Expires = 0;
ctx.Response.Buffer = true;
ctx.Response.Clear ();
MemoryStream memStream = new MemoryStream ((byte[])arr);
memStream.WriteTo (ctx.Response.OutputStream);
memStream.Close ();
ctx.Response.ContentType = "image/png";
ctx.Response.StatusCode = 200;
ctx.Response.End ();
}
}
}