路由删除images / js / css等

时间:2011-10-25 05:20:44

标签: c# asp.net routing path

我已经this Routing开始工作了。它是Dot Net 4.0 System.Web.Routing。

但问题是文档中的所有路径都不再有效。如果我希望页面同时工作

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   路线(“agents / graphics / {folder} / {filename}。{ext}”,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/

1 个答案:

答案 0 :(得分:0)

确保RegisterRoutes()方法中的第一件事是:

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

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