| 1234567891011121314151617181920212223242526272829303132333435363738394041 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace SharedKernel.Extensions
- {
- public static class QueryStringExtension
- {
- public static string ToQueryString(this object obj)
- {
- if (obj is null)
- {
- return string.Empty;
- }
- var properties = obj.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).Where(p => p.GetValue(obj) != null);
- var query = new StringBuilder('?');
- foreach (var prop in properties)
- {
- var value = prop.GetValue(obj);
- if (value is null)
- {
- continue;
- }
- if (query.Length > 1)
- {
- query.Append('&');
- }
- query.Append(Uri.EscapeDataString(prop.Name));
- query.Append('=');
- query.Append(Uri.EscapeDataString(value.ToString()!));
- query.Append("&");
- }
- return query.Length > 1 ? query.ToString().TrimEnd('&') : string.Empty;
- }
- }
- }
|