Returning ObjectID as a string from ASP.NET Core

6k views Asked by At

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();
}
2

There are 2 answers

1
Chirdeep Tomar On BEST ANSWER

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

0
Elijah On

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; }