jgiacomini / Tiny.RestClient

Simpliest Fluent REST client for .NET
MIT License
210 stars 30 forks source link

Add Form Properties by object #116

Open auriou opened 3 years ago

auriou commented 3 years ago

I suggest you a feature to add properties in a form by passing a class. this can also be used for querystring and multipart stringcontent

public IFormRequest AddFormParameters<TParameters>(TParameters parameters)
    where TParameters : class
{
    if (_formParameters == null)
    {
        _formParameters = new List<KeyValuePair<string, string>>();
        _content = new FormParametersContent(_formParameters, null);
    }

    foreach (var property in typeof(TParameters).GetProperties())
    {
        var getValue = property.GetValue(parameters);
        string value = null;
        if (getValue != null)
        {
            if (IsGenericList(property.PropertyType))
            {
                var values = (IEnumerable)getValue;
                value = string.Join(",", values.OfType<object>());
            }
            else if (property.PropertyType == typeof(DateTime)
                     || property.PropertyType == typeof(DateTime?))
            {
                value = ((DateTime)getValue).ToString("s");
            }
            else
            {
                value = getValue.ToString();
            }
        }

        if (!string.IsNullOrEmpty(value))
        {
            _formParameters.Add(new KeyValuePair<string, string>(property.Name, value));
        }
    }

    return this;
}

public static bool IsGenericList(Type type)
{
    if (type == null)
    {
        throw new ArgumentNullException(nameof(type));
    }

    foreach (var @interface in type.GetInterfaces())
    {
        if (@interface.IsGenericType)
        {
            if (@interface.GetGenericTypeDefinition() == typeof(IList<>))
            {
                return true;
            }
        }
    }

    return false;
}