绝对URL的相对路径的一般解决方案?

时间:2015-04-14 09:47:09

标签: c# uri

我有一个 Uri实例来自某个请求。 我有“〜/ Pages / SomePage.aspx”

var uri = new Uri("http://www.contoso.com/");
var relativeUrl = "~/Pages/SomePage.aspx";

如何轻松地将两者结合起来?

你可能会问,上下文是什么?这是一个控制台应用程序,其中Uri和波浪形相对路径是手动构建的(这实际上是获得“通用解决方案”的谎言,而不是Page.Resolve等)。

我尝试了一些东西(IE:HttpStyleUriParser)但我没有得到正确的结果。我不希望String.Format("{0}://{1}{2}{3}")在那里。

2 个答案:

答案 0 :(得分:0)

在* nix系统中~使用了波形符home directory of currect user

在.Net / C#/ Windows应用程序中,您必须将其替换为当前用户的主目录。

答案 1 :(得分:0)

这对我有用:

static class Program
{
    static void Main(string[] args)
    {

        var uri = new Uri("http://www.contoso.com/");
        var relativeUrl = new Uri("~/Pages/SomePage.aspx".Replace("~",string.Empty),UriKind.Relative);
        Uri result;
        bool success = Uri.TryCreate(uri, relativeUrl,out result);

        Console.WriteLine(success);
        Console.WriteLine(result.ToString());
    }

}

输出:

  

     

http://www.contoso.com/Pages/SomePage.aspx