2

How to you get a string representation of the ObjectId returned via ASP.NET Core.

I have the following result of an action in my controller:

return new ObjectResult(new { session, user });

One of the user properties is the UserId that is of the ObjectId type.

However, this gets returned in the response as

"id": {
  "timestamp": 1482840000,
  "machine": 6645569,
  "pid": 19448,
  "increment": 5052063,
  "creationTime": "2016-12-27T12:00:00Z"
}

I would like the response to simply be 58625d5201c4f202609fc5f3 that is the string representation of the same structure.

Are there any easy way to do this for all returned ObjectIds?

EDIT Adding some more data

Here are the user class. ObjectId is MongoDB.Bson.ObjectId

public class User
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string PasswordHash { get; set; }
    public string PasswordSalt { get; set; }
}

The get method in my controller. Controller is Microsoft.AspNetCore.Mvc.Controller.

[HttpGet("{id}", Name = "GetUser")]
public async Task<IActionResult> Get(ObjectId id)
{
    var user = await _repository.GetOne<User>(id);
    if (user == null) return NotFound();
    return new ObjectResult(user);
}

And this is the method from my repository:

public async Task<T> GetOne<T>(ObjectId id)
{
    var collectionname = typeof(T).Name;
    var collection = _database.GetCollection<T>(collectionname);
    var filter = Builders<T>.Filter.Eq("_id", id);
    var result = await collection.Find(filter).ToListAsync();
    return result.FirstOrDefault();
}
11
  • ObjectId should be serialised to string by default Commented Dec 27, 2016 at 12:53
  • It's not apparently. I have not set up anything special here, but this is what I get back from the service. Commented Dec 27, 2016 at 12:54
  • try doing .ToString() on the Id property explicitly. As far as I know .NET Core internally uses JSON.net which should have taken care of it. Can you share your Document, Repository & Service code. Commented Dec 27, 2016 at 12:57
  • I added some more information to my post now. However manual ToString is not a solution for me, since it's part of the object returned, and this problem is the same for all objects having a objectid, and I don't want to add random ToString calls all over the place . Commented Dec 27, 2016 at 13:05
  • You dont use BSON library ?? I mean thats the json parser for mongo db which handles the serilization of objectId internally. mongodb.github.io/mongo-csharp-driver/2.2/reference/bson/… Commented Dec 27, 2016 at 13:07

2 Answers 2

3

You have to explicitly write a ObjectID to JSON convertor. Please check the link below: https://stackoverflow.com/a/37966098/887976

Sign up to request clarification or add additional context in comments.

1 Comment

Note that to register this in ASP.NET Core you will have to add the following in your ConfigureServices method: services.AddJsonOptions(opt => {opt.SerializerSettings.Converters.Add(new ObjectIdConverter());});
0

If you need to use the string representation of an objectId, try changing the type of the field to use string first like so

// [BsonId] // use if primary key is not Id
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.