2009-07-16 3 views
34

私は車輪を再発明しているような気がしているので、私はここで群衆に尋ねると思った。私はこのようなコードスニペットを持って想像:パーツを使用してC#でURLを確実に構築するにはどうすればよいですか?

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 

私はURLを構築したい「http://www.google.com/plans/worlddomination.html」。どこにも

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

私は、これはどこかの.NETフレームワークの中に存在すると信じなきゃ、しかし:私は本当に欲しい

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

のようなAPIのいくつかの並べ替えです:私はこのような安っぽいコードを書くことで、これをやり続けるん私は出会った。

絶対に不正な形式のURLを作成するにはどうすればよいですか?

+0

読むアレックス・ブラックの答えは、ここをクリックします。http://social.msdn Microsoft.com/Search/en-US /?洗練度= 27%2c117&クエリ= Uri + Builder –

答えて

24

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を含んでいます。

PM> Install-Package Flurl.Http

または単にスタンドアロンURLビルダー:フルパッケージがNuGetで利用可能です

PM> Install-Package Flurl

関連する問題