您的位置:首页 > 其它

变化的相对路径处理

2017-03-21 15:08 218 查看
 ASP.NET中 使用Server.Transfer转移到别的地址;或使用自定义控件时。会出现相对地址不一定的情况。这时使用图片,Css文件或其他与相对路径相关的资源,就会出错。

  处理这种情况需要使用代码。需要在Page上定义这样一个属性

[c-sharp] view
plain copy

public string CurrentPath  

    {  

        get  

        {  

            //return "../";  

            string fileBase = HttpContext.Current.Request.PhysicalApplicationPath;  

            string askFile = HttpContext.Current.Request.PhysicalPath;  

            if (!askFile.Contains(fileBase))  

                return string.Empty;//错误。可以修改为异常  

            string xdpath = askFile.Replace(fileBase,"");  

            xdpath = xdpath.Replace('//', '/');  

            int lasPos = 0;  

            string rT = string.Empty ;  

            for (int i = 0; i < xdpath.Length; i++)  

            {  

                if (xdpath[i] == '/')  

                {  

                    if (lasPos != i)  

                        rT += "../";  

                    lasPos = i;  

                }  

            }  

  

            return rT;  

        }  

    }  

  

  该属性能够自动监测客户端页面的地址,生成相对路径。如果你有自定义的Page类,那么写在MyPage上会更方便。

 

使用时把原来的地址变为<%= CurrentPath +"从根开始的相对路径" %>

 

例如原来有一个背景图片: style="background-image:url('Imags/loginBg.jpg');"

需要修改为:style="background-image:url('<%= CurrentPath +"Imags/loginBg.jpg"%>');"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: