Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

c# - Combining URIs and Paths

I am retro-fitting an application to make use of a PHP HTTP proxy (for caching) instead of the actual API server, the application currently combines the server URI and the path with the code:

methodUri = new Uri(apiUri, method.Path)

Where:

The result of the above statement is

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

To use the PHP HTTP proxy the request would have to be changed as follows

The output I was expecting was:

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

However the output I get is:

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

I understand that this is the correct functionality of the constructor Uri(Uri, string), my question is what would be a better function or constructor to use in its place to get the output I expect? I have tried removing the leading "/" in method.Path taking it from an absolute path to a relative path however that did not help.

NOTE: both solutions below do work, however System.UriBuilder provides a more robust mechanism for combining URI's and paths and in my case resulted in fewer changes to resources than using System.Uri. Had I the choice I would mark both answers as correct.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't use the Uri object, use a UriBuilder - it copes way better with missing slashes

So

Uri apiUri = new Uri("http://www.r-s.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());

works as expected and produces http://www.r-s.co.uk/eproxy.php/char/SkillIntraining.xml.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...