我需要组合两个包含.Path信息的URL.
我想使用Uri给我.TryCreate()的可能性,所以我可以捕获格式错误的URL.
我面临的问题是,当我合并绝对URI和相对URI时,基本的URI路径似乎被忽略了:
Uri absoluteUri= new Uri("http://hostname/path/",UriKind.Absolute); Uri relativeUri = new Uri("/my subsite/my page.aspx?my=query",UriKind.Relative); Uri resultUri; if (!Uri.TryCreate(absoluteUri,relativeUri,out resultUri)) // handle errors
以上输出是:
http://hostname/my%20subsite/my%20page.aspx?my=query
我希望它是:
http://hostname/path/my%20subsite/my%20page.aspx?my=query
有没有办法组合使用Uri类包含路径信息的URL?
解决方法
您的相对URI应该是相对的,即删除第一个斜杠(或添加句点),
string relative = "/my subsite/my page.aspx?my=query"; Uri test1= new Uri(relative.Substring(1),UriKind.Relative); // without 'root' Uri test2= new Uri("." + relative,UriKind.Relative); // with 'current'
工作范例:
Uri baseUri = new Uri("http://hostname/path/"); string relative = "/my subsite/my page.aspx?my=query"; Uri test1 = new Uri(baseUri,relative); // original string Uri test2 = new Uri(baseUri,relative.Substring(1)); // without 'root' character Uri test3 = new Uri(baseUri,"." + relative); // with 'current' character Console.WriteLine(test1.OriginalString); // wrong Console.WriteLine(test2.OriginalString); // right! Console.WriteLine(test3.OriginalString); // right!
所以,你可能应该像这样处理你的相关部分:
if (relative.StartsWith("/")) relative = "." + relative;