2

我正在尝试构建一个以友好方式返回图像的处理程序,例如http://mydomain.com/images/123/myimage.jpg甚至 .../123/myimage

在使用 .NET Forms 和 ashx 文件之前,我曾这样做过。

我现在正在使用 MVC 4(我是新手)并且正在尝试做同样的事情。我重新使用了很多旧代码,并在我的项目中添加了一个 ashx 文件,并通过查询字符串成功生成了我的图像。但是,我就是无法让 Url Rewrite 工作!

在我的旧代码中,我使用了:

        RouteTable.Routes.MapHttpHandlerRoute("imagestoret", "imagestore/{fileId}", "~/Images/ImageHandler.ashx");
        RouteTable.Routes.Add(new Route("imagestore/{fileId}", new PageRouteHandler("~/Images/ImageHandler.ashx")));

其中 MapHttpHandlerRoute 是在 Internet 上找到的自定义类,其中包含:

    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (!string.IsNullOrEmpty(_virtualPath))
        {
            return (IHttpHandler)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(IHttpHandler));
        }
        else
        {
            throw new InvalidOperationException("HttpHandlerRoute threw an error because the virtual path to the HttpHandler is null or empty.");
        }
    }

从那以后,我尝试将其转换为与查询字符串一起成功工作的控制器,但是,当我尝试在其中添加路由时,仍然返回 404 错误。

routes.MapRoute(
            "ImageProvider",
            "imagestore/{fileId}/",
            new { controller = "File", action = "GetFile", id = UrlParameter.Optional });

我还尝试了 Internet 上的 ImageRouteHandler:

    public class ImageRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        // Do stuff
    }
}

然后将以下内容添加到我的 RouteConfig.cs 中:

        routes.Add("MyImageHandler",
            new Route("imagex/{fileId}",
            new ImageRouteHandler())
        );

有谁知道我要去哪里错了?

提前致谢。

4

1 回答 1

2

我还没有找到一个完美的解决方案,但有一个妥协。如果没有 {controller} 方面,我根本无法让路线工作。所以我最后做的是添加一条新路线:

        routes.MapRoute(
            "FileProvider",
            "{controller}/{action}/{id}/{name}",
            new { controller = "File", action = "GetFile", id = UrlParameter.Optional },
            new[] { "mynamespace.Controllers" }
        );

这允许路由到我的 Controller > FileController > GetFile 方法,例如

    public FileResult GetFile(int id, string name)
    {
        DB.UploadedFile file;

        file = DB.UploadedFile.GetFile(4, DB.UploadedFile.UploadedFileType.IMAGE, id, name);

        if (file != null && DB.UploadedFile.IsImage(file.Filename))
        {
            ImageFormat imgFormat = GetImageFormat(file.Extension);

            if (imgFormat != ImageFormat.Icon)
            {
                return File(file.FileContentsAsByteArray, file.ContentType);
            }
        }
        return null;
    }

因此,这使我可以提供以下图像:

http://mydomain.com/File/GetFile/1/DogsAndCats

该代码确保 id 和 name 匹配,因此人们不能只搜索文件数据库。

目前该文件没有扩展名,这可能会导致问题,但到目前为止 - 只要设置了内容类型),图像就会正确加载。

在我的代码中还有更多工作要做以服务其他文件类型,但也许这种妥协对其他人有用。

于 2013-04-10T10:28:11.437 回答