Skip to content
This repository has been archived by the owner on Dec 18, 2018. It is now read-only.

ConfigurationBinder cannot set properties with type 'object' #511

Closed
VitaliyMF opened this issue Sep 11, 2016 · 0 comments
Closed

ConfigurationBinder cannot set properties with type 'object' #511

VitaliyMF opened this issue Sep 11, 2016 · 0 comments
Assignees

Comments

@VitaliyMF
Copy link

VitaliyMF commented Sep 11, 2016

When settings model has property of type 'object', ConfigurationBinder throws InvalidOperationException ('Failed to convert 'VALUE' to type 'System.Object').
I think this is a bug, because property with type 'object' can accept value of any type.

If settings model has a property with array of another model that has property of type 'object', this array entry is ignored (because of 'catch {}' code, see below).

Steps to reproduce

Settings models:

public class MySettingsWithArray {
    public MySettings[] Lst { get; set; }
}
public class MySettings {
    public object Id { get; set; }
}

appsettings.json:

{
  "TEST": {
    "Id" : 5
  },
 "TEST2" : {
  "Lst": [  { "Id" : 5  } ]
 }
}

Bind code that works incorrectly:

IConfigurationRoot Configuration; // lets assume this is our app config
var testOpts = new MySettings();
Configuration.GetSection("TEST").Bind(testOpts);  // throws an exception, but 

var test2Opts = new MySettingsWithArray();
Configuration.GetSection("TEST2").Bind(test2Opts); 
// test2Opts.Lst[0] is null , exception is not thrown

Exception may be fixed with simple type check in ConfigurationBinder.ConvertValue(Type type, string value).

Both array & collection de-serialization methods (ConfigurationBinder.BindArray, ConfigurationBinder.BindCollection) have a code that ignores any exceptions during array/collection members deserialization:

for (int i = 0; i < children.Length; i++)
            {
                try
                {
                    var item = BindInstance(
                        type: elementType,
                        instance: null,
                        config: children[i]);
                    if (item != null)
                    {
                        newArray.SetValue(item, arrayLength + i);
                    }
                }
                catch
                {
                }
            }

This is definitely weird behaviour, when in some cases ConfigurationBinder.Bind throws an exceptions, and when array/collection is used they are ignored.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants