【问题标题】:Why not into RouteHandler ?为什么不进入 RouteHandler ?
【发布时间】:2016-10-13 04:11:39
【问题描述】:

我正在尝试写一个关于“防止图像窃取”的演示, 参考资源: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();
    }
}

【问题讨论】:

  • 这里可以复制ImageRouteHandler.cs的相关部分吗?仅具有文章链接的问题是文章可能会更改,或者该链接在将来可能无效。此外,它使我们更容易提供帮助,因为我们不必搜索您在说什么。
  • 已修改帖子,谢谢!
  • 您还可以发布您遇到的错误吗?仍然不清楚您所说的“不起作用”是什么意思。

标签: asp.net-mvc iroutehandler


【解决方案1】:

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

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

...无效。

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

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

顺便提一下,注意你的开发者工具的网络标签;这将使您看到所有请求(例如您的图像请求)和响应。说它“不起作用”或类似的说法是没有用的。事情永远不会“不起作用”;他们只是做一些你期望之外的事情。更好的描述应该是“我收到 404 错误”或“我的图片请求没有发出”。

【讨论】:

    猜你喜欢
    • 2010-12-18
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2017-09-02
    • 1970-01-01
    相关资源
    最近更新 更多