Uri.TryCreate不会产生我期望的结果

时间:2012-01-23 13:46:19

标签: c# uri

我正在抓取网站的URL和锚标签都将其href值设置为查询字符串,例如..

<a href="?AppId=12345&CatId=13">Details</a>

当前页面的URL是这样的..

http://www.theurl.com/ThePage.aspx?PageNo=2

因此,我正在寻找的网址将是

http://www.theurl.com/ThePage.aspx?AppId=12345&CatId=13

为了得到这个,我使用方法Uri.TryCreate,所以我传入以下参数(前两个参数是Uri类型而不是字符串)..

Uri.TryCreate("http://www.theurl.com/ThePage.aspx?PageNo=2", "?AppId=12345&CatId=13", out uri);

然而out参数'uri'被设置为..

http://www.theurl.com/?AppId=12345&CatId=13

如您所见,它会删除.aspx路径。您能否推荐一种更好的方法来解决这个问题,或解释为什么它不能按照我的想法运作?

2 个答案:

答案 0 :(得分:1)

试试这个:

Uri.TryCreate("http://www.theurl.com/ThePage.aspx?PageNo=2", "ThePage.aspx?AppId=12345&CatId=13", out uri);

根据the docs,第一个是基URI,第二个是相对URI。

答案 1 :(得分:0)

嗯。我不确定发生的行为是否正确。这可能是一个错误。

在任何情况下,您都可以找到以下方法:

UriBuilder uBuild = new UriBuilder("http://www.theurl.com/path/thePage.aspx?PageNo=2");
uBuild.Query = "AppId=12345&CatId=13";
Uri newUri = ub.Uri;//http://www.theurl.com/path/thePage.aspx?AppId=12345&CatId=13
//Note that we can reuse uBuild as we continue to parse the page, as long as we're only dealing with cases where only the query changes.
uBuild.Query = "AppId=678&CatId=2";
Uri anotherUri = ub.Uri;//http://www.theurl.com/path/thePage.aspx?AppId=678&CatId=2
相关问题