c# - 从 IHttpHandler(通用处理程序)中的文件路径获取 URL

标签 c# asp.net httphandler

在我的 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) { }

最佳答案

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

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");
    }
}

关于c# - 从 IHttpHandler(通用处理程序)中的文件路径获取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5845358/

相关文章:

c# - XDocument XDeclaration 未出现在 ToString 结果中

php - 防止在达到最小高度或粘贴文本时创建新的 div

c# - 使用 asp.net 遍历文本框

c# - 如何使用 Facebook 登录应用程序

Asp.net 自定义 http 处理程序位于另一个 ashx http 处理程序之前

c# - "The process can not access the file ' ... ' because it is being used by another process"重新创建临时文件以使用 FtpWebRequest 上传

c# - 从 C# 中的字符串中提取基本 URl?

c# - 我将如何为我的应用程序窗口的一部分拍摄快照?

ASP.Net 4.0 - 如何从 ASHX 内访问 RouteData?

iis-7 - 如何在 IIS 经典模式池下托管 ASP.NET 5 (vNext) MVC 6 项目