Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an "not configured as an allowed type for this instance of ObjectSerializer" serialization error

I'm working on an integration project. I get an error while inserting the entity to the mongodb.

The error message return this string below :

MongoDB.Bson.BsonSerializationException: 'An error occurred while serializing the OrderData property of class Order: Type MarketplaceOrder is not configured as an allowed type for this instance of ObjectSerializer.'

A few steps before, I'm getting data from any api resources and converting the data to my generic object <T> like below line.

var data = (JArray)returnDataFromNetwork.Data;
var order = data.ToObject<T>()

I get the error while inserting the entity to the mongodb

_orderRepository.InsertAsync(new Order
  {
    OrderData = order,
  });
public class Order
{
  public object OrderData { get; set; }
}

public class MarketplaceOrder
{
  [JsonProperty("marketplace")]
  public string Marketplace { get; set; }

  [JsonProperty("account_id")]
  public int AccountId { get; set; }
}

Thanks for your support,

The all the things which I try to explain is on "hangfire" (background service) project. First I get this error message on server console. Then I tried to debug locally to understand where the issue is. I could not understand the error message detail.

like image 262
mrkiyak Avatar asked Dec 02 '25 06:12

mrkiyak


1 Answers

I think you use 2.19 .net driver. See release notes with the description of your issue.

The ObjectSerializer has been changed to only allow deserialization of types that are considered safe. What types are considered safe is determined by a new configurable AllowedTypes function (of type Func<Type, bool>). The default AllowedTypes function is ObjectSerializer.DefaultAllowedTypes which returns true for a number of well-known framework types that we have deemed safe. A typical example might be to allow all the default allowed types as well as your own types. This could be accomplished as follows:

The solution:

var objectSerializer = new ObjectSerializer(type => ObjectSerializer.DefaultAllowedTypes(type) || type.FullName.StartsWith("MyNamespace"));
BsonSerializer.RegisterSerializer(objectSerializer);
like image 157
dododo Avatar answered Dec 03 '25 20:12

dododo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!