Search code examples
c#asp.net-coreconfigurationappsettingsasp.net-core-5.0

Ignore model property when binding with ASP.NET Core Options service


I'm using the Options service to bind hierarchical configuration data.

But suppose I have a class like this:

public class PersonOptions
{

  public string Name { get; set; }

  public int Age { get; set; }

  public bool Foo {               // <--- I want binder to ignore this
    get {
      // ... do stuff
    }
  }

  public bool IgnoreMe =>         // <--- I want binder to ignore this
    throw new Exception();

}

Because the Foo property is public, the binder runs it and triggers some code that throws exceptions.

My design requires it to be public, and I prefer not to change it to a method.

Is there some attribute or override I can use to tell the binder to ignore that property?


Solution

  • The docs state:

    All public read-write properties of the type are bound

    If the property is public, then for some reason the binder runs it. Also, [JsonIgnore] isn't respected.

    So unless I'm missing something obvious, this cannot be done.

    The workarounds are:

    • use a non-public property
    • use a method instead of a property

    I've added a feature request to the repo to support an "ignore" attribute.

    UPDATE:
    They've added the feature request to the backlog, so I assume what I wanted cannot be done, currently.