示例#1
0
        public static FormattedRoute Format(Route route, object[] arguments = null, IEnumerable <KeyValuePair <string, object> > queryParameters = null)
        {
            var formatter = new RouteFormatter();
            var builder   = new StringBuilder();

            // We use the formatter with string.Format() and it'll collect all encountered parameters with their names.
            builder.AppendFormat(formatter, route.Path, arguments ?? Array.Empty <object>());

            if (queryParameters != null)
            {
                var first = true;
                foreach (var parameter in queryParameters)
                {
                    if (string.IsNullOrWhiteSpace(parameter.Key))
                    {
                        throw new ArgumentException("Query parameters must not contain null or whitespace keys.");
                    }

                    var value = parameter.Value;
                    if (value == null)
                    {
                        throw new ArgumentException("Query parameters must not contain null values.");
                    }

                    builder.Append(first ? '?' : '&');
                    builder.Append(parameter.Key);
                    builder.Append('=');
                    if (value is IEnumerable enumerable and not string)
                    {
                        builder.AppendJoin(',', enumerable.Cast <object>());
                    }
                    else
                    {
                        builder.Append(Uri.EscapeDataString(value.ToString()));
                    }
                    first = false;
                }
示例#2
0
 public static FormattedRoute Format(this Route route, object[] arguments = null, IEnumerable <KeyValuePair <string, object> > queryParameters = null)
 => RouteFormatter.Format(route, arguments, queryParameters);