The built-in `IPAddressSerializer` throws when using `IPAddress.Any`, etc.

XMLWordPrintableJSON

    • Type: Bug
    • Resolution: Fixed
    • Priority: Unknown
    • 3.7.0
    • Affects Version/s: None
    • Component/s: None
    • None
    • None
    • Fully Compatible
    • C Drivers
    • Not Needed
    • Hide

      1. What would you like to communicate to the user about this feature?
      2. Would you like the user to see examples of the syntax and/or executable code and its output?
      3. Which versions of the driver/connector does this apply to?

      Show
      1. What would you like to communicate to the user about this feature? 2. Would you like the user to see examples of the syntax and/or executable code and its output? 3. Which versions of the driver/connector does this apply to?
    • None
    • None
    • None
    • None
    • None
    • None

      .NET's standard `System.Net.IPAddress` class has an obscure nested subtype called `ReadOnlyIPAddress`, which is used for readonly static fields on `IPAddress` such as `IPAddress.Any`, `IPAddress.Loopback`, and others — see the source here.

      The MongoDB.Driver's built-in `MongoDB.Bson.Serialization.Serializers.IPAddressSerializer` doesn't work for such instances. The minimal one-liner repro would be this:

      IPAddress.Any.ToBson(BsonSerializer.LookupSerializer<IPAddress>())

      Which when run currently throws a `BsonSerializationException` with the following message:

      > An error occurred while serializing the ScopeId property of class System.Net.IPAddress: Operation not supported

      This hints that the built-in `IPAddressSerializer` isn't even used in this case. I dug a little deeper and found out that the base class from which `IPAddressSerializer` derives (i.e. `ClassSerializerBase`) bypass the serialization method by default if the nominal type of the value isn't identical to its runtime type — see this.

      This little quirk wasted a few hours of my time. The same issue existed a few years ago for .NET's `System.Text.Json`'s serializer, which was reported and subsequently fixed here. Please consider doing the same.

            Assignee:
            Oleksandr Poliakov
            Reporter:
            Arad Alvand
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: