Posts

Showing posts from February 16, 2019

Convert a custom object to a query string

Image
8 0 I wrote an extension method that takes a custom object and converts its properties to a query string for use in a URL. You can specify what properties you want included by using a [QueryString] attribute. For example: class Thing { [QueryString] public int Id {get; set;} [QueryString] public string Name {get; set;} public object MetaData {get; set;} } var thing = new Thing { Id = 1, Name = "Test", MetaData = someObj }; thing.ToQueryString(); // outputs `?Id=1&Name=Test Here's the code for the extension method: public static string ToQueryString(this object obj) { StringBuilder queryStringBuilder = new StringBuilder("?"); Type objType = obj.GetType(); // Get properties marked with `[QueryString]` List<PropertyInfo> props = o