简体   繁体   English

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

[英]General solution for relative ~path to absolute url?

I have a Uri instance from some request. 我有一些要求的Uri实例 And I've got "~/Pages/SomePage.aspx" . 而且我有“〜/ Pages / SomePage.aspx”

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

How do I combine the two easily? 如何轻松地将两者结合?

What's the context, you may ask? 您可能会问什么背景? It's a console application where the Uri and the tilde relative path are manually constructed (that's actually a lie to get a "General solution", and not an Page.Resolve, etc. one). 它是一个控制台应用程序,在其中手动构建了Uri和代字号相对路径(实际上,这是获得“常规解决方案”的谎言,而不是Page.Resolve等)。

I tried a few things (IE: HttpStyleUriParser) but I didn't get the right result. 我尝试了一些方法(即IE:HttpStyleUriParser),但没有得到正确的结果。 And I don't want to String.Format("{0}://{1}{2}{3}") my way there. 而且我不想用String.Format("{0}://{1}{2}{3}")到达那里。

The tilde character ~ is used in *nix systems for home directory of currect user . 波浪号~在* nix系统中用于home directory of currect user

In a .Net/C#/Windows application you must replace it by current user's home directory. 在.Net / C#/ Windows应用程序中,您必须将其替换为当前用户的主目录。

This works for me: 这对我有用:

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

}

Output: 输出:

True 真正

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

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

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