2011-10-25 37 views
0

我已经得到this Routing工作。它是Dot Net 4.0 System.Web.Routing。路由删除图像/ js/css等

但问题是文档中的所有路径不再有效。如果我想的页面都作为

www.website.com/agents/Agent Name 

和“真”地址

www.website.com/portfolio.aspx?aid=123 

我该怎么办?当然,我可以通过使用绝对URL,如

<img src="http://www.website.com/images/image.png" alt="" /> 

但是这是要走的路?


我居然发现自己的答案:

routes.Add( “AgentFolderGraphicsRoute”,新 路线( “代理/图形/ {文件夹}/{文件名} {}分机”, new ImageRouteHandler()));


public class ImageRouteHandler : IRouteHandler 
    { 
     public IHttpHandler GetHttpHandler(RequestContext requestContext) 
     { 
      string folder = requestContext.RouteData.Values["folder"] as string; 
      string filename = requestContext.RouteData.Values["filename"] as string; 
      string ext = requestContext.RouteData.Values["ext"] as string; 

      if (string.IsNullOrEmpty(filename)) 
      { 
       requestContext.HttpContext.Response.Clear(); 
       requestContext.HttpContext.Response.StatusCode = 404; 
       requestContext.HttpContext.Response.End(); 
      } 
      else 
      { 
       requestContext.HttpContext.Response.Clear(); 
       requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString()); 

       // find physical path to image here. 
       string filepath; 
       if (folder != null) filepath = requestContext.HttpContext.Server.MapPath("~/graphics/" + folder + "/" + filename + "." + ext); 
       else filepath = requestContext.HttpContext.Server.MapPath("~/graphics/" + filename + "." + ext); 

       requestContext.HttpContext.Response.WriteFile(filepath); 
       requestContext.HttpContext.Response.End(); 
      } 
      return null; 
     } 

     private static string GetContentType(String path) 
     { 
      switch (System.IO.Path.GetExtension(path)) 
      { 
       case ".bmp": return "Image/bmp"; 
       case ".gif": return "Image/gif"; 
       case ".jpg": return "Image/jpeg"; 
       case ".png": return "Image/png"; 
       default: break; 
      } 
      return ""; 
     } 

这是一个此页面上的稍作修改的版本:

http://www.phpvs.net/2009/08/06/aspnet-mvc-how-to-route-to-images-or-other-file-types/

回答

0

让你RegisterRoutes()方法确定的第一件事就是:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

这将指示路由引擎忽略资源请求(如图像或文件)。

+0

我不这么认为,我可以在非MVC应用程序中这样做。 – Jesper

+0

MVC实际上只是一个ASP.NET扩展。 MVC中的路由引擎与WebForms中的路由引擎相同,因此它应该可以工作。你试过了吗? –

+0

我不能,因为System.Web.Routing.RouteCollection不包含IgnoreRoute – Jesper