如何从url字符串中删除端口号

时间:2010-05-12 13:44:07

标签: c# asp.net

我有以下代码段:

string tmp = String.Format("<SCRIPT FOR='window' EVENT='onload' LANGUAGE='JavaScript'>javascript:window.open('{0}');</SCRIPT>", url);

ClientScript.RegisterClientScriptBlock(this.GetType(), "NewWindow", tmp);

此代码生成的URL包含端口号,我认为正在发生这种情况,因为网站使用了端口80,在此代码中我尝试从网站的虚拟目录加载页面。有关如何抑制此代码生成的URL字符串中的端口号的任何想法吗?

8 个答案:

答案 0 :(得分:120)

使用Uri.GetComponents方法。要删除端口组件,您必须组合所有其他组件,例如:

var uri = new Uri( "http://www.example.com:80/dir/?query=test" );
var clean = uri.GetComponents( UriComponents.Scheme | 
                               UriComponents.Host | 
                               UriComponents.PathAndQuery, 
                               UriFormat.UriEscaped );
编辑:我找到了一个更好的方法:

var clean = uri.GetComponents( UriComponents.AbsoluteUri & ~UriComponents.Port,
                               UriFormat.UriEscaped );

UriComponents.AbsoluteUri保留所有组件,因此& ~UriComponents.Port只会排除端口。

答案 1 :(得分:67)

UriBuilder u1 = new UriBuilder( "http://www.example.com:80/dir/?query=test" );
u1.Port = -1;
string clean = u1.Uri.ToString();

Port上将-1属性设置为UriBuilder将删除任何显式端口,并隐式使用协议方案的默认端口值。

答案 2 :(得分:32)

基于Ian Flynn idea的更通用的解决方案(适用于http,https,ftp ...)。 此方法不会删除自定义端口(如果有)。 根据协议自动定义自定义端口。

var uriBuilder = new UriBuilder("http://www.google.fr/");
if (uriBuilder.Uri.IsDefaultPort)
{
    uriBuilder.Port = -1;
}
return uriBuilder.Uri.AbsoluteUri;

答案 3 :(得分:8)

我会使用System.Uri来做这件事。我没试过,但似乎ToString实际上会输出你想要的东西:

var url = new Uri("http://google.com:80/asd?qwe=asdff");
var cleanUrl = url.ToString();

如果没有,您可以合并url - 成员的组件来创建cleanUrl字符串。

答案 4 :(得分:4)

var url = "http://google.com:80/asd?qwe=zxc#asd";
var regex = new Regex(@":\d+");
var cleanUrl = regex.Replace(url, "");

使用System.Uri的解决方案也是可能的,但会更加臃肿。

答案 5 :(得分:1)

您也可以使用the properties URIBuilder来获取此信息,它具有按您希望的方式输出网址的属性

答案 6 :(得分:1)

好的,谢谢我想出来......用了KISS原则......

string redirectstr = String.Format(
   "http://localhost/Gradebook/AcademicHonestyGrid.aspx?StudentID={0}&ClassSectionId={1}&uid={2}", 
   studid, 
   intSectionID, 
   HttpUtility.UrlEncode(encrypter.Encrypt(uinfo.ToXml())));

Response.Redirect(redirectstr );

可以正常使用我正在做的测试工具

答案 7 :(得分:1)

您可以使用UriBuilder并将端口的值设置为-1

,代码将如下所示:

Uri tmpUri = new Uri("http://LocalHost:443/Account/Index");
UriBuilder builder = new UriBuilder(tmpUri);
builder.Port = -1;
Uri newUri = builder.Uri;