您可以像这样在处理程序中执行身份验证/授权逻辑。
例如,如果用户未登录,以下代码将显示 404 错误。
public class ImageHandler : IHttpHandler, IRequiresSessionState
{
// 1x1 transparent GIF
private readonly byte[] GifData =
{
0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
0x01, 0x00, 0x01, 0x00, 0x80, 0xff,
0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
0x02, 0x44, 0x01, 0x00, 0x3b
};
public void ProcessRequest(HttpContext context)
{
//if (context.User.IsInRole("Administrators"))
if (context.User.Identity.IsAuthenticated)
{
context.Response.ContentType = "image/gif";
context.Response.Buffer = false;
context.Response.OutputStream.Write(GifData, 0, GifData.Length);
}
else
{
context.Response.Write("File not found.");
context.Response.StatusCode = 404;
}
}
public bool IsReusable
{
get { return false; }
}
}