如何从URI中删除PROTOCOL

Him*_*ack 28 c# asp.net

如何从URI中删除协议?即删除HTTP

Kri*_*aes 54

你可以System.Uri像这样使用这个类:

System.Uri uri = new Uri("http://stackoverflow.com/search?q=something");
string uriWithoutScheme = uri.Host + uri.PathAndQuery + uri.Fragment;
Run Code Online (Sandbox Code Playgroud)

这将为您提供stackoverflow.com/search?q=something

编辑:这也适用于:空白 :-)

  • 有"Uri.Authority",即"Uri.Host"+"Uri.Port". (9认同)
  • 如果您假设端口80,这可以正常工作,否则在Uri类上有一个Port属性,应该检查然后附加前面的冒号. (3认同)
  • 您可以使用 uri.GetLeftPart 并从方案中提取子串,而不是连接内容。例如 `string uriWithoutScheme = uri.ToString().Substring(uri.GetLeftPart(UriPartial.Scheme).Length);` 或者其他什么? (2认同)

Mar*_*ell 13

一般意义上(不限于http/https),(绝对)uri总是一个方案后面跟一个冒号,然后是方案特定的数据.因此,唯一安全的做法是削减计划:

    string s = "http://stackoverflow.com/questions/4517240/";
    int i = s.IndexOf(':');
    if (i > 0) s = s.Substring(i + 1);
Run Code Online (Sandbox Code Playgroud)

对于http和其他一些您可能也想要的情况.TrimStart('/'),但这不是该方案的一部分,并且不保证存在.琐碎的例子:about:blank.

  • 很好,你包括解释不总是修剪'/'. (3认同)

Ron*_*ald 11

最好的(也是我最漂亮的)方法是使用Uri类将字符串解析为绝对URI,然后使用GetComponents具有正确UriComponents枚举的方法来删除方案:

Uri uri;
if (Uri.TryCreate("http://stackoverflow.com/...", UriKind.Absolute, out uri))
{
    return uri.GetComponents(UriComponents.AbsoluteUri &~ UriComponents.Scheme, UriFormat.UriEscaped);
}
Run Code Online (Sandbox Code Playgroud)

有待进一步参考:UriComponents枚举是用它装饰的FlagsAttribute,因此可以在其上使用按位运算(例如.&|).在这种情况下,&~删除比特UriComponents.SchemeUriComponents.AbsoluteUri与位补运算符组合使用AND运算符.