我有一个使用 ImageHandler 输出图像的 asp.net Web 表单应用程序。基本上是为了防止盗取,但也是为了从另一台服务器获取图像文件。
下面是 ProcessRequest 的实现:
public void ProcessRequest(HttpContext ctx)
{
HttpRequest req = ctx.Request;
string path = req.PhysicalPath.ToLower();
string extension = Path.GetExtension(path);
if (req.UrlReferrer != null && req.UrlReferrer.Host.Length > 0)
{
if (CultureInfo.InvariantCulture.CompareInfo.Compare(req.Url.Host, req.UrlReferrer.Host, CompareOptions.IgnoreCase) != 0)
{
path = ctx.Server.MapPath("~/images/noimage.jpg");
}
}
// Rewrite path if not in production
if (imagePath != null)
{
if (path.Length > path.IndexOf("\\images\\", StringComparison.Ordinal) + 7)
{
string end = path.Substring(path.IndexOf("\\images\\", StringComparison.Ordinal) + 7);
path = string.Concat(imagePath, end).Replace("\\", "/");
}
}
string contentType;
switch (extension)
{
case ".gif":
contentType = "image/gif";
break;
case ".jpg":
contentType = "image/jpeg";
break;
case ".png":
contentType = "image/png";
break;
default:
throw new NotSupportedException("Unrecognized image type.");
}
if (!File.Exists(path))
{
ctx.Response.Status = "Image not found";
ctx.Response.StatusCode = 404;
}
else
{
ctx.Response.StatusCode = 200;
ctx.Response.ContentType = contentType;
ctx.Response.WriteFile(path);
}
}
上面的代码失败是因为我想将路径重写为 url 而不是文件路径。我想重写的原因是因为实际的图像文件在另一台服务器上,不能通过 UNC 路径访问。我做错了什么,有可能做到这一点吗?
干杯