为什么不进入 RouteHandler ?

Why not into RouteHandler ?

我正在尝试编写有关 "Prevent Image Leeching" 的演示, 参考资源:http://www.mikesdotnetting.com/article/126/asp-net-mvc-prevent-image-leeching-with-a-custom-routehandler

但是当我使用 <img src="~/graphics/a.png" /> 时, ImageRouteHandler.cs 将不起作用。 不幸的是,这个 ImageRouteHandler.cs 还行不通。 为什么 ??

public class ImageRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new ImageHandler(requestContext);
    }
}

public class ImageHandler : IHttpHandler
{
    public ImageHandler(RequestContext context)
    {
        ProcessRequest(context);
    }

    private static void ProcessRequest(RequestContext requestContext)
    {
        var response = requestContext.HttpContext.Response;
        var request = requestContext.HttpContext.Request;
        var server = requestContext.HttpContext.Server;
        var validRequestFile = requestContext.RouteData.Values["filename"].ToString();
        const string invalidRequestFile = "thief.png";
        var path = server.MapPath("~/graphics/");

        response.Clear();
        response.ContentType = GetContentType(request.Url.ToString());

        if (request.ServerVariables["HTTP_REFERER"] != null &&
            request.ServerVariables["HTTP_REFERER"].Contains("http://localhost:8010/")) //mikesdotnetting.com
        {
            response.TransmitFile(path + validRequestFile);
        }
        else
        {
            response.TransmitFile(path + invalidRequestFile);
        }
        response.End();
    }

    private static string GetContentType(string url)
    {
        switch (Path.GetExtension(url))
        {
            case ".gif":
                return "Image/gif";
            case ".jpg":
                return "Image/jpeg";
            case ".png":
                return "Image/png";
            default:
                break;
        }
        return null;
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        throw new NotImplementedException();
    }
}

~ 不是 URL 中有意义的前缀。这有时在某些 ASP.NET 上下文中使用,例如 Server.MapPath,以引用应用程序根目录,但在 HTML 中这个 URL:

<img src="~/graphics/a.png" />

...无效。

在开头使用 / 来指代您站点的根目录,或者省略前导 / 来指代相关 URL。不清楚这是否是您遇到的唯一问题,但这是 一个 问题。这样做你可能运气更好:

<img src="/graphics/a.png" />

对了,注意你的开发者工具的网络选项卡;这将使您看到所有请求(例如您的图像请求)和响应。说 "will not work" 或类似的是没有用的。事情从不"don't work";他们只是做一些你期望之外的事情。更好的描述是 "I'm getting a 404 error" 或 "the request for my image isn't being made."