Home > other >  How to turn an object into a request in C#
How to turn an object into a request in C#

Time:05-10

My Model, example:

public class Obj
    {
        public Obj()
        { }
        public int? IdRestricao { get; set; }
        public int? IdTipoRestringido { get; set; }
        public string CodRestringido { get; set; }
        public string NomeRestringido { get; set; }
        public int? IdTipoRestricao { get; set; }
        public string CodRestricao { get; set; }
        public string NomeRestricao { get; set; }
        public DateTime? PeriodoInicio { get; set; }
        public DateTime? PeriodoFim { get; set; }
        public int? IdStatus { get; set; }
    }

Request

www.url.com.br?IdRestricao=1&IdTipoRestringido=2&CodRestringido=3&NomeRestringido=4&IdTipoRestricao=5&CodRestricao=6&NomeRestricao=7&PeriodoInicio=8&PeriodoFim=9

code:

var model = obj.*tostring()*// 
something like    
var request = new RestRequest($"/api/{**model**}", Method.GET);

edit1:

I'm wondering if there is a library or something that transforms my object in my request as in the examples above

CodePudding user response:

You can override ToString to format the data from the Obj class into GET parameters.

You could write a utility function to convert all object properties into nameof and the associated value into key-value pairs.

Something such as this answer to convert your Obj into a dictionary, and then another method to convert the dictionary into Prop=value could be done.

For a one off something like this would be suitable:

public override string ToString()
{
    return $"IdRestricao={IdRestricao}&IdTipoRestringido={IdTipoRestringido}&CodRestringido={CodRestringido}...
}

CodePudding user response:

I found the answer to what I was looking for, it follows below in case anyone needs it in the future

private static string ToQueryString(this object request, string separator = ",")
        {
            if (request == null)
                throw new ArgumentNullException("request");

            // Get all properties on the object
            var properties = request.GetType().GetProperties()
                .Where(x => x.CanRead)
                .Where(x => x.GetValue(request, null) != null)
                .ToDictionary(x => x.Name, x => x.GetValue(request, null));

            // Get names for all IEnumerable properties (excl. string)
            var propertyNames = properties
                .Where(x => !(x.Value is string) && x.Value is IEnumerable)
                .Select(x => x.Key)
                .ToList();

            // Concat all IEnumerable properties into a comma separated string
            foreach (var key in propertyNames)
            {
                var valueType = properties[key].GetType();
                var valueElemType = valueType.IsGenericType
                                        ? valueType.GetGenericArguments()[0]
                                        : valueType.GetElementType();
                if (valueElemType.IsPrimitive || valueElemType == typeof(string))
                {
                    var enumerable = properties[key] as IEnumerable;
                    properties[key] = string.Join(separator, enumerable.Cast<object>());
                }
            }

            // Concat all key/value pairs into a string separated by ampersand
            return string.Join("&", properties
                .Select(x => string.Concat(
                    Uri.EscapeDataString(x.Key), "=",
                    Uri.EscapeDataString(x.Value.ToString()))));
        }
  • Related