我不想将 HTTP 请求路由到操作,而是路由到文件。
重要提示:我确实有使用 IIS 7.0 URL 重写模块的工作解决方案,但为了在家调试(没有 IIS 7.0),我无法使用 URL 重写。
具体情况
我想将任何包含 /images/
的 URL 指向 ~/images/
文件夹。
示例:
http://wowreforge.com/images/a.png -> /images/a.png
http://wowreforge.com/Emerald Dream/Jizi/images/a.png -> /images/a.png
http://wowreforge.com/US/Emerald Dream/Jizi/images/a.png -> /images/a.png
http://wowreforge.com/characters/view/images/a.png -> /images/a.png
问题源于页面“view_character.aspx”可以从多个 URL 到达:
http://wowreforge.com/?name=jizi&reaml=Emerald Dream
http://wowreforge.com/US/Emerald Dream/Jizi
上下文 IIS 7.0(集成模式)、ASP.NET MVC 2.0
额外学分问题
- 在这种情况下使用 ASP.NET MVC 路由而不是 URL 重写是一个坏主意吗?
- IIS 7.0 使用什么处理程序将请求路由到物理文件?
最佳答案
您可能应该将图像链接重写为。
<img src="<%= ResolveUrl("~/images/a.png") %>" />
这样你就不需要让你的路由处理图像。
更新 您将如何通过路由来做到这一点 将此条目添加到您的路由表
routes.Add("images", new Route("{*path}", null,
new RouteValueDictionary(new { path = ".*/images/.*"}),
new ImageRouteHandler()));
现在您需要创建一个 ImageRouteHandler 和一个 ImageHandler
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//you'll need to figure out how to get the physical path
return new ImageHandler(/* get physical path */);
}
}
public class ImageHandler : IHttpHandler
{
public string PhysicalPath { get; set; }
public ImageHandler(string physicalPath)
{
PhysicalPath = physicalPath;
}
public void ProcessRequest(HttpContext context)
{
context.Response.TransmitFile(PhysicalPath);
}
public bool IsReusable
{
get { return true; }
}
}
这也不做任何缓存。您可以查看 Reflector 中的 System.Web.StaticFileHandler,了解处理 Asp.Net 应用程序静态文件的处理程序,以获得更完整的实现。
关于asp.net-mvc-2 - ASP.NET MVC 2.0 : route request to static resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4716574/