【问题标题】:What's the .NET equivalent of the browser's URL.origin? [duplicate]浏览器的 URL.origin 的 .NET 等价物是什么? [复制]
【发布时间】:2016-05-05 16:39:08
【问题描述】:

给定一个像https://somedomain.com:1234/someotherstuff?a=b#def这样的url,浏览器的URL类的origin属性返回https://somedomain.com:1234

var url = new URL("https://somedomain.com:1234/someotherstuff?a=b#def");
console.log(url.origin);

打印

"https://somedomain.com:1234"

.NET 中是否有等价物?

我看到了Uri 类,但它似乎没有与上面的origin 对应的字段

Uri u = new Uri("https://somedomain.com:1234/someotherstuff?a=b#def");
Console.WriteLine(u.AbsolutePath);  //  /someotherstuff
Console.WriteLine(u.AbsoluteUri);   //  https://somedomain.com:1234/someotherstuff?a=b#def
Console.WriteLine(u.Fragment);      //  #def
Console.WriteLine(u.Host);          //  somedomain.com
Console.WriteLine(u.LocalPath);     //  /someotherstuff
Console.WriteLine(u.Port);          //  1234
Console.WriteLine(u.Query);         //  ?a=b
Console.WriteLine(u.DnsSafeHost);   //  somedomain.com
Console.WriteLine(u.HostNameType);  //  Dns
Console.WriteLine(u.Scheme);        //  https

看来我需要这样做

string origin = u.Scheme + 
                "://" + 
                u.host + 
                (String.IsNullOrEmpty(u.Port) ? "" : (":" + u.Port)

可能还有其他一些我不知道的东西。

是否已经有一些跨平台(不仅限于 Windows).NET 函数可以为我提供相当于 URL.origin 的功能?

【问题讨论】:

  • 我在发布并投票结束后立即找到了答案。令我感到难过的是,在编写问题时建议可能的答案时,显示的建议与发布问题后的建议不同。答案是Uri.GetLeftPart()

标签: .net url


【解决方案1】:

您可以替换 PathAndQuery 和 Fragments:

var url = new Uri("https://somedomain.com:1234/someotherstuff?a=b#def#a");
var newUrl = url.AbsoluteUri.Replace(url.PathAndQuery, String.Empty).Replace(url.Fragment, String.Empty);

或者你可以在授权之后切割部分:

var url = new Uri("https://somedomain.com:1234/someotherstuff?a=b#def#a");
var authorityIndex = url.AbsoluteUri.IndexOf(url.Authority);
var newUrl = url.AbsoluteUri.Substring(0, authorityIndex + url.Authority.Length);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2011-12-26
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多