操纵来自 App.config 的 url 的正确方法

Correct way of manipulating the url coming from App.config

我有一个 URL ("http://localhost:2477/") 我确实收到了 post 请求。我已将此 URL 存储在我项目的 app.config 文件中。

在代码中,根据函数的不同,我将字符串 "getValue?id={0}" 或 "postValue" 添加到此 URL。但是我后来 运行 在 app.config 中将 URL 更改为“http://localhost:2477”(最后没有正斜杠)时遇到了问题。

花了我一些尴尬的时间来弄清楚这个问题,这让我想知道是否有一个好的方法来处理这个案例。

无论 URL 中是否有正斜杠,我都希望我的代码将其更改为正确的 URL。

始终使用 Path.Combine(string, string)。此方法将符合有效路径,并应在需要时添加 /

编辑 我意识到我的答案不适用于 URL,仅适用于文件路径。

您正在寻找的是 Uri 构造函数。

Uri baseUri = new Uri("http://www.contoso.com");

Uri myUri = new Uri(baseUri, "catalog/shownew.htm");

使用 Uri class you can modify your URL more elegantly. You can access the Host, Port, Query, etc. with ease. A similar question was asked here.

尝试使用UriBuilder,它比Uri Constructor 更灵活。 参见