在这种情况下,我建议使用IHttpHandler 而不是通用的WebForm。 https://msdn.microsoft.com/en-us/library/system.web.ihttphandler(v=vs.110).aspx
处理程序更适合此请求,因为它能够快速响应,并且专为处理不一定基于 HTML 的特定请求而构建。这可以很简单地连接以接受请求、查询数据库并生成您选择的图像。现在您还没有提供太多关于图像来源的信息,但让我们看一个简单的请求。
要在 Web 表单 Web 应用程序中开始,请选择一个新的 GenericHandler,我们将其命名为 DynamicImage.ashx。这将构建我们的初始模板,如下所示。
public class DynamicImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
此模板提供了处理我们请求的基础知识。当请求到达时,WebServer 将执行ProcessRequest() 方法,传入HttpContext 作为参数。从这里我们可以使用它来传递我们的响应。
出于参数考虑,假设我们正在根据QueryString 参数username 查询图像,该参数代表我们数据库中的用户。我在您的步骤中包含了一些基本代码来实现这一点。 (代码注释)
public void ProcessRequest(HttpContext context)
{
//get our username from the query string
var username = context.Request.QueryString["username"];
//clear the response and set the content type headers
context.Response.Clear();
context.Response.ContentType = "image/png";
//if the username is empty then end the response with a 401 not found status code
if (string.IsNullOrWhiteSpace(username))
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//do a db query to validate the user. If not valid do a 401 not found
bool isValidUser = new UserManager().IsValidUser(username);
if (!isValidUser)
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//get the user image file path from a server directory. If not found end with 401 not found
string filePath = context.Server.MapPath(string.Format("~/App_Data/userimages/{0}.png", username));
if (!System.IO.File.Exists(filePath))
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//finish the response by transmitting the file
context.Response.StatusCode = 200;
context.Response.TransmitFile(filePath);
context.Response.Flush();
context.Response.End();
}
要调用此处理程序,您只需将图像的src 设置为类似于/DynamicImage.ashx?username=johndoe 的路径。
现在您的要求可能略有不同。例如,您可能从数据库中检索图像为byte[],因此您可能希望使用context.Response.BinaryWrite() 方法而不是使用context.Response.TransmitFile() 方法。此方法传输byte[] 作为响应流。
最后,我建议您参考(我的)另一篇文章,该文章从客户端的角度讨论缓存这些图像。如果您的按钮将非常频繁地生成,这将非常有用。 Leverage browser caching in IIS (google pagespeed issue)