利用.ashx文件是一个更好的方法,这个文件类似于.aspx文件,可以通过它来调用HttpHandler类,从而免去了普通.aspx页面的控件解析以及页面处理的过程。这个文件特别适合于生成动态图片,生成动态文本等内容。
ShowPhoto.ashx里面就下面一句话
<% @ WebHandler language="C#" class="AspNetResources.Owc.ChartHandler" codebehind="ShowPhoto.cs" %>
其实也可以用这个代替
在web.config里面的<system.web>里面加上
<httpHandlers>
<add verb="*" path="*.ashx" type="AspNetResources.Owc, ChartHandler " validate="false" /> /*ChartHandler 是那个ashx.cs编译后生成的代码Assembly*/
<!--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>
<%@ WebHandler Language="C#" Class="ShowPhoto" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class ShowPhoto : IHttpHandler
{
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
// Set up the response settings
context.Response.ContentType = "image/jpg";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput = false;
int photoId = -1;
Stream stream = null;
if (context.Request.QueryString["PhotoID"] != null && context.Request.QueryString["PhotoID"] != "")
{
photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
stream = GetPhoto(photoId);
}
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);
}
}
public Stream GetPhoto(int photoId)
{
string sqlPhoto = "select photo from account where userid=" + photoId;
SqlDataReader result =DFBDSql.GetReader(sqlPhoto);
result.Read();
return new MemoryStream((byte[])result["photo"]);
}
}