为这些图像提供HttpHandler - 这样您就可以从您的网络应用程序可以访问的任何文件夹(包括数据库或某些库中的嵌入式资源)中提供图像。
假设通用处理程序将被命名为 ImageHandler.ashx:
public class ImageHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
const string folder = @"c:\Attachments";
string fileName = context.Request.QueryString["FileName"];
var path = Path.Combine(folder, fileName);
var mapping = new Dictionary<string, string> {
{ ".gif", "image/gif" },
{ ".jpg", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".png", "image/png" },
{ ".bmp", "image/bmp" }
};
var info = new DirectoryInfo(Path.GetDirectoryName(path));
if (!info.FullName.StartsWith(folder, StringComparison.OrdinalIgnoreCase)) {
// someone is using .. to hack our path - send him away
context.Response.StatusCode = 404;
context.Response.End();
return;
}
if (!File.Exists(path)) {
// file not found - 404
context.Response.StatusCode = 404;
context.Response.End();
return;
}
// set some client caching - you can skip this if you don't want to
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetExpires(DateTime.Now.AddDays(3));
var extension = Path.GetExtension(path).ToLowerInvariant();
string contentType;
if (!mapping.TryGetValue(extension, out contentType)) {
contentType = "application/octet-stream";
}
context.Response.ContentType = contentType;
context.Response.WriteFile(path);
}
public bool IsReusable {
get { return false; }
}
}
现在你可以请求像
这样的图片了
<asp:Image ID="Image2" runat="server"
ImageUrl="~/ImageHandlers.ashx?FileName=test.png" />
此外,如果您还想在服务器端缓存图像(并且如果您使用的是 IIS7),您可以在 Web 配置中设置条目,例如:
<location path="ImageHandler.ashx">
<system.webServer>
<caching>
<profiles>
<add extension=".ashx" policy="CacheForTimePeriod" duration="00:00:10" varyByQueryString="FileName" />
</profiles>
</caching>
</system.webServer>
</location>