Parsing objeto dto a query string en .Net Core

Subscribe to my newsletter and never miss my upcoming articles

Les comparto un pequeño metodo helper para parsear un objeto (DTO) a query string y poder ser usado un GET request


        public static string ToQueryString(object dto)
        {
            var type = dto.GetType();
            var data = type
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .ToDictionary(
                    p => p.Name,
                    p => p.GetValue(dto)
                );
            var query = HttpUtility.ParseQueryString(String.Empty);

            foreach (var d in data.Where(d => d.Value != null))
            {
                if ((!(d.Value is string)) && d.Value is IEnumerable enumerable)
                {
                    foreach (var value in enumerable)
                    {
                        query.Add(d.Key, value.ToString());
                    }
                }
                else
                {
                    query.Add(d.Key, d.Value.ToString());
                }
            }

            var queryString = query.ToString();

            return $"?{queryString}";
        }

objeto DTO:

    public class MyDto
    {
        public int? Size { get;set; }
        public int? Page { get;set; }
    }

ejemplo de uso:


            var queryParameters = new MyDto{ Size = 100, Page = 1 };
            var query = ToQueryString(queryParameters);
            var url = $"https://jsonplaceholder.typicode.com/todo/search{query}";

No Comments Yet