Bjoern
Bjoern

Reputation: 164

Building URI with the http client API

I have to build a URI address with dynamic query strings and looking for a comfortable way to build them via code.

I browsed the System.Net.Http assembly but doesn't found a class or method for this case. Does this API not provide this? My search results here at StackOverflow uses the HttpUtility class from the System.Web, but I don't want to reference any ASP.Net components in my class library.

I need a URI like this : http://www.myBase.com/get?a=1&b=c.

Thanks in advance for helping!

Update (2013/9/8):

My solution was to create a URI builder that uses System.Net.WebUtilitiy class for encoding the values (The imported NuGet package unfortunately didn't provide a strong name key). Here's my code :

/// <summary>
/// Helper class for creating a URI with query string parameter.
/// </summary>
internal class UrlBuilder
{
    private StringBuilder UrlStringBuilder { get; set; }
    private bool FirstParameter { get; set; }

    /// <summary>
    /// Creates an instance of the UriBuilder
    /// </summary>
    /// <param name="baseUrl">the base address (e.g: http://localhost:12345)</param>
    public UrlBuilder(string baseUrl)
    {
        UrlStringBuilder = new StringBuilder(baseUrl);
        FirstParameter = true;
    }

    /// <summary>
    /// Adds a new parameter to the URI
    /// </summary>
    /// <param name="key">the key </param>
    /// <param name="value">the value</param>
    /// <remarks>
    /// The value will be converted to a url valid coding.
    /// </remarks>
    public void AddParameter(string key, string value)
    {
        string urlEncodeValue = WebUtility.UrlEncode(value);

        if (FirstParameter)
        {
            UrlStringBuilder.AppendFormat("?{0}={1}", key, urlEncodeValue);
            FirstParameter = false;
        }
        else
        {
            UrlStringBuilder.AppendFormat("&{0}={1}", key, urlEncodeValue);
        }

    }

    /// <summary>
    /// Gets the URI with all previously added paraemter
    /// </summary>
    /// <returns>the complete URI as a string</returns>
    public string GetUrl()
    {
        return UrlStringBuilder.ToString();
    }
}

Hope this helps somebody here at StackOverflow. My request is working.

Björn

Upvotes: 2

Views: 5929

Answers (3)

Todd Menier
Todd Menier

Reputation: 39329

Flurl [disclosure: I'm the author] is a portable class library sporting a fluent API for building and (optionally) calling URLs:

using Flurl;
using Flurl.Http; // if you need it

var url = "http://www.myBase.com"
    .AppendPathSegment("get")
    .SetQueryParams(new { a = 1, b = "c" }) // multiple
    .SetQueryParams(dict)                   // multiple with an IDictionary
    .SetQueryParam("name", "value")          // one by one

    // if you need to call the URL with HttpClient...

    .WithOAuthBearerToken("token")
    .WithHeaders(new { a = "x", b = "y" })
    .ConfigureHttpClient(client => { /* access HttpClient directly */ })
    .PostJsonAsync(new { first_name = firstName, last_name = lastName });

Querystring values are URL-encoded in each case. Flurl also included is a nifty set of HTTP testing features. The full package is available on NuGet:

PM> Install-Package Flurl.Http

or just the stand-alone URL builder:

PM> Install-Package Flurl

Upvotes: 2

Darrel Miller
Darrel Miller

Reputation: 142174

If you take a dependency on Tavis.Link you can use URI Templates to specify parameters.

    [Fact]
    public void SOQuestion18302092()
    {
        var link = new Link();
        link.Target = new Uri("http://www.myBase.com/get{?a,b}");

        link.SetParameter("a","1");
        link.SetParameter("b", "c");

        var request = link.CreateRequest();
        Assert.Equal("http://www.myBase.com/get?a=1&b=c", request.RequestUri.OriginalString);
        
        
    }

There are some more examples of what you can do with Tavis.Link on the Github repo.

Upvotes: 2

Jacob
Jacob

Reputation: 3698

Query String:

To write data:

Server.Transfer("WelcomePage.aspx?FirstName=" + Server.UrlEncode(fullName[0].ToString()) +
                                        "&LastName=" + Server.UrlEncode(fullName[1].ToString()));

To get the written Data:

Server.UrlDecode(Request.QueryString["FirstName"].ToString()) + " "
                                                + Server.UrlDecode(Request.QueryString["LastName"].ToString());

Upvotes: 0

Related Questions