Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple URL builder for C#
//+ Jonas Raoni Soares Silva
//@ http://raoni.org
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace JonasRaoni
{
class UrlBuilder
{
private readonly string _path;
private readonly NameValueCollection _queryCollection = HttpUtility.ParseQueryString(string.Empty);
public UrlBuilder(string path) => _path = path;
[UsedImplicitly]
public UrlBuilder AddQueryParam(string name, string? value)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Value cannot be null or empty.", nameof(name));
}
if (string.IsNullOrEmpty(value))
{
return this;
}
_queryCollection.Add(name, value);
return this;
}
public override string ToString()
{
var query = _queryCollection.ToString();
return string.IsNullOrEmpty(query) ? _path : $"{_path}?{query}";
}
}
static class UrlBuilderExtensions
{
public static UrlBuilder AddQueryParam<T>(this UrlBuilder builder, string name, IEnumerable<T>? values)
{
if (values != null)
{
foreach (var value in values)
{
builder.AddQueryParam(name, value?.ToString());
}
}
return builder;
}
public static UrlBuilder AddQueryParam(this UrlBuilder builder, string name, IEnumerable<long?>? values)
{
foreach (var value in values ?? Enumerable.Empty<long?>())
{
builder.AddQueryParam(name, value?.ToString(CultureInfo.InvariantCulture));
}
return builder;
}
public static UrlBuilder AddQueryParam(this UrlBuilder builder, string name, IEnumerable<decimal?>? values)
{
foreach (var value in values ?? Enumerable.Empty<decimal?>())
{
builder.AddQueryParam(name, value?.ToString(CultureInfo.InvariantCulture));
}
return builder;
}
public static UrlBuilder AddQueryParam(this UrlBuilder builder, string name, bool? value)
{
builder.AddQueryParam(name, value?.ToString());
return builder;
}
public static UrlBuilder AddQueryParam(this UrlBuilder builder, string name, Enum? value)
{
builder.AddQueryParam(name, value?.ToString());
return builder;
}
public static UrlBuilder AddQueryParam(this UrlBuilder builder, string name, decimal? value)
{
builder.AddQueryParam(name, value?.ToString(CultureInfo.InvariantCulture));
return builder;
}
public static UrlBuilder AddQueryParam(this UrlBuilder builder, string name, long? value)
{
builder.AddQueryParam(name, value?.ToString(CultureInfo.InvariantCulture));
return builder;
}
public static UrlBuilder AddQueryParam(this UrlBuilder builder, string name, DateTimeOffset? value)
{
if (value != null)
{
builder.AddQueryParam(name, value.Value.ToUniversalTime().ToString("s", CultureInfo.InvariantCulture) + "Z");
}
return builder;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment