【问题标题】:How to reliably build a URL in C# using the parts?如何使用这些部件在 C# 中可靠地构建 URL?
【发布时间】:2010-11-11 05:13:08
【问题描述】:

我一直觉得我在重新发明轮子,所以我想我应该问问这里的人群。想象一下,我有一个这样的代码 sn-p:

string protocol = "http"; // Pretend this value is retrieved from a config file
string host = "www.google.com"; // Pretend this value is retrieved from a config file
string path = "plans/worlddomination.html"; // Pretend this value is retrieved from a config file

我想建立网址“http://www.google.com/plans/worlddomination.html”。我一直在写这样的俗气的代码来做到这一点:

protocol = protocol.EndsWith("://") ? protocol : protocol + "://";
path = path.StartsWith("/") ? path : "/" + path;    
string fullUrl = string.Format("{0}{1}{2}", protocol, host, path);

我真正想要的是某种 API,例如:

UrlBuilder builder = new UrlBuilder();
builder.Protocol = protocol;
builder.Host = host;
builder.Path = path;
builder.QueryString = null;
string fullUrl = builder.ToString();

我必须相信这存在于 .NET 框架中的某个地方,但我没有遇到过。

构建万无一失(即从不畸形)网址的最佳方法是什么?

【问题讨论】:

标签: c# url


【解决方案1】:

【讨论】:

    【解决方案2】:

    UriBuilder 非常适合处理 URL 前面的位(如协议),但在查询字符串方面不提供任何内容。 Flurl [披露:我是作者] 试图用一些流畅的优点来填补这个空白:

    using Flurl;
    
    var url = "http://www.some-api.com"
        .AppendPathSegment("endpoint")
        .SetQueryParams(new {
            api_key = ConfigurationManager.AppSettings["SomeApiKey"],
            max_results = 20,
            q = "Don't worry, I'll get encoded!"
        });
    

    有一个新的配套库 extends the fluent chain with HTTP client calls 并包含一些漂亮的 testing features。 NuGet 上提供了完整的包:

    PM> Install-Package Flurl.Http

    或只是独立的 URL 构建器:

    PM> Install-Package Flurl

    【讨论】:

      猜你喜欢
      • 2022-12-11
      • 2015-05-27
      • 2012-10-21
      • 2021-07-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多