我正在尝试构建一个以友好方式返回图像的处理程序,例如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())
);
有谁知道我要去哪里错了?
提前致谢。