我需要在 ASP.net 中创建一个可以嵌入到另一个网页中的按钮。
本质上,该按钮将在页面加载时查询数据库服务器端,然后根据查询的返回更改其图像。
有人知道最好的方法吗?如您所知,我不是 ASP.net 的专家。最好用 C# 编写。
最佳答案
在这种情况下,我建议使用 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.TransmitFile()
方法而不是使用 code>context.Response.BinaryWrite()
方法。此方法传输一个 byte[]
作为响应流。
最后,我建议您参阅(我的)另一篇文章,该文章从客户端的角度讨论了缓存这些图像。如果您的按钮生成非常频繁,这将非常有用。 Leverage browser caching in IIS (google pagespeed issue)
关于c# - 在 ASP.net 中创建嵌入式图像按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31061670/