2

I am using Audit.Net package for auditing requirements for my application. https://github.com/thepirat000/Audit.NET/tree/master/src/Audit.NET.MongoDB#auditnetmongodb

I am facing JSON Serialization exception, when I try to use the AuditScope.Create method. Attached is the exception I get. What am I missing?

Below is the class UserProfiles:

    public class UserProfiles
    {
        [BsonId]
        public ObjectId Id { get; set; }
        public int UserId { get; set; }
        [BsonRequired]
        public string UserName { get; set; }
        [BsonRequired]
        public string Password { get; set; }
        public string Role { get; set; }
        [BsonRequired]
        public string Email { get; set; }
        [BsonRequired]
        public string ProjectId { get; set; }
    }

enter image description here

Startup.cs file: below is code used:

public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            Audit.Core.Configuration.DataProvider = new Audit.MongoDB.Providers.MongoDataProvider()
            {
                ConnectionString = "mongodb://localhost:27017",
                Database = "Audit",
                Collection = "Event"
            };
        }

I tried moving the dataprovider configuration to ConfigureServices method as well. I get the same error. Anything I am missing?

Thanks, Vani

  • Could you share the `UserProfiles` class code? Are you declaring any property as `ObjectId`? – thepirat000 Apr 30 '20 at 20:31
  • Also wondering if [this](https://stackoverflow.com/a/37966098/122195) solves your problem (creating a `JsonConverter` and overriding the `MongoDataProvider.JsonSerializerSettings` property) – thepirat000 Apr 30 '20 at 20:39
  • @thepirat000: Yes ```UserProfiles``` class has ```ObjectId``` property. – Vani Kulkarni May 01 '20 at 04:39

1 Answers1

0

The problem is the ObjectId cannot be serialized/deserialized to Json using the default serializer for the Target Object.

The latest version of the Mongo Data Provider includes a setting SerializeAsBson you should set to true, so your target object is serialized as a Bson Document.

Audit.Core.Configuration.DataProvider = new Audit.MongoDB.Providers.MongoDataProvider()
{
    ConnectionString = "mongodb://localhost:27017",
    Database = "Audit",
    Collection = "Event",
    SerializeAsBson = true
};
thepirat000
  • 12,362
  • 4
  • 46
  • 72