结合URI和路径

我正在改造应用程序以使用PHP HTTP代理(用于缓存)而不是实际的API服务器,应用程序当前将服务器URI和路径与代码组合在一起:

methodUri = new Uri(apiUri, method.Path) 

哪里:

  • apiUri =“ http://api.eve-online.com/ ”(System.Uri对象)
  • method.Path =“/ char / SkillIntraining.xml.aspx”(string)

上述陈述的结果是

 "http://api.eve-online.com/char/SkillIntraining.xml.aspx" (System.Uri Object) 

要使用PHP HTTP代理,必须按如下方式更改请求

  • apiUri =“ http://www.rs.co.uk/eproxy.php ”(System.Uri对象)
  • method.Path =“/ char / SkillIntraining.xml.aspx”(string)

我期待的输出是:

 "http://www.rs.co.uk/eproxy.php/char/SkillIntraining.xml.aspx" (System.Uri Object) 

但是我得到的输出是:

 "http://www.rs.co.uk/char/SkillIntraining.xml.aspx" (System.Uri Object) 

我知道这是构造函数Uri(Uri,string)的正确function,我的问题是什么是更好的函数或构造函数来使用它来获得我期望的输出? 我已经尝试删除method.Path中的前导“/”,将其从绝对路径带到相对路径但是没有帮助。

注意:下面的两个解决方案都可以工作,但是System.UriBuilder提供了一个更强大的机制来组合URI和路径,在我的情况下,与使用System.Uri相比,对资源的更改更少。 如果我选择我会将两个答案标记为正确。

不要使用Uri对象,使用UriBuilder – 它可以更好地处理丢失的斜杠

所以

 Uri apiUri = new Uri("http://www.rs.co.uk/eproxy.php"); string methodPath = "/char/SkillIntraining.xml.aspx"; System.UriBuilder uriBuilder = new System.UriBuilder(apiUri); uriBuilder.Path += methodPath; Console.WriteLine(uriBuilder.Uri.ToString()); 

按预期工作并生成http://www.rs.co.uk/eproxy.php/char/SkillIntraining.xml.aspx

在apiUri中添加一个尾随的“/”,并从method.Path中删除前导“/”:

  Uri apiUri = new Uri("http://www.rs.co.uk/eproxy.php/"); string path = "char/SkillIntraining.xml.aspx"; Uri uri = new Uri(apiUri, path); Console.WriteLine(uri.ToString());