【问题标题】:Getting URL from file path in IHttpHandler (Generic handler)从 IHttpHandler 中的文件路径获取 URL(通用处理程序)
【发布时间】:2011-08-16 06:22:14
【问题描述】:

在我的 IHttpHandler 类(对于 .ashx 页面)中,我想在目录中搜索某些文件,并返回相对 url。我可以得到文件,没问题:

string dirPath = context.Server.MapPath("~/mydirectory");
string[] files = Directory.GetFiles(dirPath, "*foo*.txt");
IEnumerable<string> relativeUrls = files.Select(f => WHAT GOES HERE? );

将文件路径转换为相对 url 的最简单方法是什么?如果我在一个 aspx 页面中,我可以说this.ResolveUrl()。我知道我可以进行一些字符串解析和字符串替换来获取相对 url,但是有没有一些内置方法可以为我处理所有这些?

编辑:澄清一下,不做我自己的字符串解析,我该怎么做:

"E:\Webs\WebApp1\WebRoot\mydirectory\foo.txt"

到这里:

"/mydirectory/foo.txt"

我正在寻找现有的方法,例如:

public string GetRelativeUrl(string filePath) { }

【问题讨论】:

标签: c# asp.net httphandler


【解决方案1】:

我可以想象很多人都有这个问题......我的解决方案是:

public static string ResolveRelative(string url)
{
    var requestUrl = context.Request.Url;
    string baseUrl = string.Format("{0}://{1}{2}{3}", 
        requestUrl.Scheme, requestUrl.Host, 
        (requestUrl.IsDefaultPort ? "" : ":" + requestUrl.Port), 
        context.Request.ApplicationPath);

    if (toresolve.StartsWith("~"))
    {
        return baseUrl + toresolve.Substring(1);
    }
    else
    {
        return new Uri(new Uri(baseUrl), toresolve).ToString();
    }
}

更新

或者从文件名到虚拟路径(还没有测试过;您可能还需要一些类似于上面的 ResoveRelative 的代码......如果它有效,请告诉我):

public static string GetUrl(string filename)
{
    if (filename.StartsWith(context.Request.PhysicalApplicationPath))
    {
        return context.Request.ApplicationPath +     
            filename.Substring(context.Request.PhysicalApplicationPath.Length);
    }
    else 
    {
        throw new ArgumentException("Incorrect physical path");
    }
}

【讨论】:

  • 您的方法从相对 url 返回绝对 url。我正在从文件路径中寻找相对 url。
  • 您可以将上述方法与 context.Request.PhysicalApplicationPath 结合使用,从而为您提供应用程序的根。
【解决方案2】:

试试System.Web.Hosting.HostingEnvironment.MapPath方法,它是静态的,可以在Web应用程序的任何地方访问。

【讨论】:

  • 这是我的物理路径,与context.Server.MapPath() 相同。我已经有了物理路径,想获取相对url,类似于Control.ResolveUrl()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
相关资源
最近更新 更多