13

I often end up rolling my own wrapper/extension methods for/around System.Uri and was wondering if anyone knows of a good open source implementation. What I like to do most is parse querystring parameters, build a new query string (this is the key), and replace page names. Got any good ones, or is System.Uri good enough for you?

Trent
  • 2,122
  • 1
  • 24
  • 38

7 Answers7

15

BradVin's QueryString Builder class is good. Fluent interface and support for encryption.

It's also worth checking out this UrlBuilder class on CodeProject. Similar to System.UriBuilder has better support for working with the QueryString.

Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
  • Kudos on this answer. This is almost verbatim what I've been rolling with for years. Don't like the UriBuilder because I want more functionality around dynamically adding qs parameters. – Trent Nov 18 '09 at 23:51
12

Flurl [disclosure: I'm the author] is a fluent URL builder that looks like this:

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!"
    });

If you happen to be building URLs for the purpose of calling them, Flurl.Http is a companion lib that lets you do HTTP off the fluent chain:

await "https://api.mysite.com"
    .AppendPathSegment("person")
    .SetQueryParams(new { ap_key = "my-key" })
    .WithOAuthBearerToken("MyToken")
    .PostJsonAsync(new { first_name = firstName, last_name = lastName });

Get the full package on NuGet:

PM> Install-Package Flurl.Http

or just the stand-alone URL builder:

PM> Install-Package Flurl

Todd Menier
  • 37,557
  • 17
  • 150
  • 173
6

We do use our own alternative Uri class that is partially based on Uri, as you say. However, I think there's an important distinction to be made - System.Uri is generally intended to be immutable - or, more precisely, behave immutably. Once one comes into existence, it represents a precise universal location/resource endpoint. If you need to describe a different location, you should create a new Uri, not change the existing one.

There's a separate class that specializes in producing Uri's: UriBuilder.

Rex M
  • 142,167
  • 33
  • 283
  • 313
3

Between System.Uri and System.UriBuilder, what features exactly are you missing from those two?

Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
  • Uri is immutable like Rex M clarified. But I didn't even know about UriBuilder. Will look into it. – Trent Nov 18 '09 at 23:41
2
    /// <summary>
    /// The arguments must be like: varName1, varValue1, varName2, varValue2 and so on.
    /// Empty names will be not be added to the result.
    /// Returns a string of the form varName1=varValue1&varName2=varValue2...
    /// </summary>    
    public static string BuildQueryString(params string[] strings)
    {
        Debug.Assert(0 == strings.GetLength(0) % 2);

        StringBuilder builder = new StringBuilder(50);
        bool isName = true;
        bool isEmptyName = false;

        foreach (string crtString in strings)
        {
            isEmptyName = (isName && string.IsNullOrEmpty(crtString)) ||
                (!isName && isEmptyName);

            if (!isEmptyName)
            {
                builder.Append(HttpUtility.UrlEncode(crtString));

                if (isName)
                    builder.Append("=");
                else
                    builder.Append("&");
            }

            isName = !isName;
        }

        return builder.ToString();
    }
Cosmin
  • 2,365
  • 2
  • 23
  • 29
1

There is a very nice new open source project on CodePlex that allows you to read, write, encrypt Uris and a bit more. Check them out!

http://querystrings.codeplex.com

cesar
  • 141
  • 1
  • 3
0

I'm not sure exactly what you are trying to do (examples would help) but it sounds like you are trying to get some of the functionality of Apache's mod_rewrite in ASP.NET.

There is an article at MSDN about exactly this.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452