diff --git a/Test/Flurl.Test/CommonExtensionsTests.cs b/Test/Flurl.Test/CommonExtensionsTests.cs index 7a949bf..ff2da71 100644 --- a/Test/Flurl.Test/CommonExtensionsTests.cs +++ b/Test/Flurl.Test/CommonExtensionsTests.cs @@ -98,6 +98,35 @@ namespace Flurl.Test Assert.Throws(() => obj.ToKeyValuePairs()); } + private class ToKvMe + { + public string Read1 { get; private set; } + public string Read2 { get; private set; } + + private string PrivateRead1 { get; set; } = "c"; + public string PrivateRead2 { private get; set; } + + public string WriteOnly { + set { + Read1 = value.Split(',')[0]; + Read2 = value.Split(',')[1]; + } + } + } + + [Test] + public void object_to_kv_ignores_props_not_publicly_readable() { + var kv = new ToKvMe { + PrivateRead2 = "foo", + WriteOnly = "a,b" + }.ToKeyValuePairs(); + + CollectionAssert.AreEquivalent(new Dictionary { + { "Read1", "a" }, + { "Read2", "b" } + }, kv); + } + [Test] public void SplitOnFirstOccurence_works() { var result = "hello/how/are/you".SplitOnFirstOccurence('/'); diff --git a/src/Flurl/Util/CommonExtensions.cs b/src/Flurl/Util/CommonExtensions.cs index f6a0903..aeb0112 100644 --- a/src/Flurl/Util/CommonExtensions.cs +++ b/src/Flurl/Util/CommonExtensions.cs @@ -16,8 +16,10 @@ namespace Flurl.Util public static class CommonExtensions { /// - /// Converts an object's public properties to a collection of string-based key-value pairs. If the object happens - /// to be an IDictionary, the IDictionary's keys and values converted to strings and returned. + /// Returns a key-value-pairs representation of the object. + /// For strings, URL query string format assumed and pairs are parsed from that. + /// For objects that already implement IEnumerable<KeyValuePair>, the object itself is simply returned. + /// For all other objects, all publicly readable properties are extracted and returned as pairs. /// /// The object to parse into key-value pairs /// @@ -50,7 +52,7 @@ namespace Flurl.Util } /// - /// Splits at the first occurence of the given seperator. + /// Splits at the first occurence of the given separator. /// /// The string to split. /// The separator to split on. @@ -74,12 +76,16 @@ namespace Flurl.Util private static IEnumerable> ObjectToKV(object obj) { #if NETSTANDARD1_0 return from prop in obj.GetType().GetRuntimeProperties() - let val = prop.GetValue(obj, null) + let getter = prop.GetMethod + where getter?.IsPublic == true + let val = getter.Invoke(obj, null) select new KeyValuePair(prop.Name, val); #else - return from prop in obj.GetType().GetProperties() - let val = prop.GetValue(obj, null) - select new KeyValuePair(prop.Name, val); + return from prop in obj.GetType().GetProperties() + let getter = prop.GetGetMethod(false) + where getter != null + let val = getter.Invoke(obj, null) + select new KeyValuePair(prop.Name, val); #endif }