zoukankan      html  css  js  c++  java
  • web中绝对路径换虚拟路径

    最近在做一个web项目,将图片上传到服务器后,再访问时拿到的是绝对路劲,而需要的是虚拟路劲。经过一番折腾找到了下列方法可以直接转换。

     /// <summary>
            /// 将Web站点下的绝对路径转换为虚拟路径
            /// 注:非Web站点下的则不转换
            /// </summary>
            /// <param name="page">当前页面指针,一般为this</param>
            /// <param name="specifiedPath">绝对路径</param>
            /// <returns>虚拟路径, 型如: ~/</returns>
            public static string ConvertSpecifiedPathToRelativePath(Page page, string specifiedPath)

            {
                string virtualPath = page.Request.ApplicationPath;

                string pathRooted = HostingEnvironment.MapPath(virtualPath);

                if (!Path.IsPathRooted(specifiedPath) || specifiedPath.IndexOf(pathRooted) == -1)
                {
                    return specifiedPath;
                }

                if (pathRooted.Substring(pathRooted.Length - 1, 1) == "\")
                {
                    specifiedPath = specifiedPath.Replace(pathRooted, "~/");
                }
                else
                {
                    specifiedPath = specifiedPath.Replace(pathRooted, "~");
                }
                string relativePath = specifiedPath.Replace("\", "/").Substring(1, specifiedPath.Length - 1);
                return relativePath;
            }

    备注:  string relativePath = specifiedPath.Replace("\", "/").Substring(1, specifiedPath.Length - 1); 里面的 Substring(1, specifiedPath.Length - 1)是我自己加的。根据自己需求。原来是string relativePath = specifiedPath.Replace("\", "/");

  • 相关阅读:
    .Net EF中DbContext动态生成DbSet
    .net core 3.0 中间件或过滤器中读取post请求body方法
    Asp.Net Core 5 WebAPI发布后的Swagger不显示问题
    .net Core 使用Swagger 让某些接口不显示在文档
    C# Request.InputStream 读取输入流为空的原因处理
    ASP.NET 中的缓存
    缓存依赖(文件、数据库)
    NLTK基本使用
    NLTK基本使用
    NLTK的基本使用
  • 原文地址:https://www.cnblogs.com/bin521/p/7133296.html
Copyright © 2011-2022 走看看