繁体   English   中英

返回到网络相对路径的绝对路径

[英]Absolute path back to web-relative path

如果我已设法使用 Server.MapPath 找到并验证文件是否存在,并且我现在想将用户直接发送到该文件,那么将该绝对路径转换回相对 Web 路径的最快方法是什么?

也许这可能会奏效:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);

我正在使用c#但可以适应vb。

使用Server.RelativePath(路径)不是很好吗?

好吧,你只需要扩展它;-)

public static class ExtensionMethods
{
    public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
    {
        return path.Replace(context.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/");
    }
}

有了它,你可以简单地打电话

Server.RelativePath(path, Request);

我知道这是旧的,但我需要考虑虚拟目录(根据@Costo的评论)。 这似乎有助于:

static string RelativeFromAbsolutePath(string path)
{
    if(HttpContext.Current != null)
    {
        var request = HttpContext.Current.Request;
        var applicationPath = request.PhysicalApplicationPath;
        var virtualDir = request.ApplicationPath;
        virtualDir = virtualDir == "/" ? virtualDir : (virtualDir + "/");
        return path.Replace(applicationPath, virtualDir).Replace(@"\", "/");
    }

    throw new InvalidOperationException("We can only map an absolute back to a relative path if an HttpContext is available.");
}

我喜欢Canoas的想法。 不幸的是我没有“HttpContext.Current.Request”(BundleConfig.cs)。

我改变了这样的方法:

public static string RelativePath(this HttpServerUtility srv, string path)
{
     return path.Replace(HttpContext.Current.Server.MapPath("~/"), "~/").Replace(@"\", "/");
}

如果您使用了Server.MapPath,那么您应该已经拥有相对Web路径。 根据MSDN文档 ,此方法采用一个变量path ,即Web服务器的虚拟路径。 因此,如果您能够调用该方法,则应该已经可以立即访问相对Web路径。

对于asp.net核心,我编写了帮助类来获得两个方向的修补程序。

public class FilePathHelper
{
    private readonly IHostingEnvironment _env;
    public FilePathHelper(IHostingEnvironment env)
    {
        _env = env;
    }
    public string GetVirtualPath(string physicalPath)
    {
        if (physicalPath == null) throw new ArgumentException("physicalPath is null");
        if (!File.Exists(physicalPath)) throw new FileNotFoundException(physicalPath + " doesn't exists");
        var lastWord = _env.WebRootPath.Split("\\").Last();
        int relativePathIndex = physicalPath.IndexOf(lastWord) + lastWord.Length;
        var relativePath = physicalPath.Substring(relativePathIndex);
        return $"/{ relativePath.TrimStart('\\').Replace('\\', '/')}";
    }
    public string GetPhysicalPath(string relativepath)
    {
        if (relativepath == null) throw new ArgumentException("relativepath is null");
        var fileInfo = _env.WebRootFileProvider.GetFileInfo(relativepath);
        if (fileInfo.Exists) return fileInfo.PhysicalPath;
        else throw new FileNotFoundException("file doesn't exists");
    }

从Controller或服务注入FilePathHelper并使用:

var physicalPath = _fp.GetPhysicalPath("/img/banners/abro.png");

反之亦然

var virtualPath = _fp.GetVirtualPath(physicalPath);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM