Aspnetcore.docs: Bug in Update method

Created on 10 Jan 2019  Â·  4Comments  Â·  Source: dotnet/AspNetCore.Docs

When trying to update a book with an HTTP PUT using e.g. URL http://localhost:54978/api/books/5c377ee3abdf6607f491228c
and JSON body
{
"id": "5c377ee3abdf6607f491228c",
"bookName": "Design Patterns UPDATED",
"price": 111.93,
"category": "Computers",
"author": "Ralph Johnson"
}

you'll get a conversion error on the Id in the book parameter since it cannot automatically be converted to an ObjectId. However, omitting the id row in the JSON body still does not work since the ID is never set in Book object in the BookService Update method before the ReplaceOne method is run in the database. You'll get a MongoWriteException because the ObjectId is 0. Just setting the Id on the Book object solves the problem.

The other way to solve it would be be able to keep the Book Id as a string in the JSON body and for the Id string to be converted to an ObjectId type somehow by the framework. Is that possible to achieve plugging in a transformer or something in the MVC request pipeline? Otherwise I guess you always would have to get rid of the ObjectId on the Book objects before sending it to the server in various update scenarios (in a more advanced scenario). Kind of a bummer...


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

P2 Source - Docs.ms

Most helpful comment

Hello @Toby9876 ,
Thanks for bringing up the issue. This issue can be solved by "Keeping the id as string". You can decorate the id with "BsonRepresentation".

`

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

`
After doing this, some changes in 'BookServices.cs' will be required.

@Rick-Anderson I'll try to update the code in sample and docs over the weekend.

All 4 comments

@prkhandelwal please review

Hello @Toby9876 ,
Thanks for bringing up the issue. This issue can be solved by "Keeping the id as string". You can decorate the id with "BsonRepresentation".

`

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

`
After doing this, some changes in 'BookServices.cs' will be required.

@Rick-Anderson I'll try to update the code in sample and docs over the weekend.

doc error
I had to add these changes along with some string to ObjectId conversion to make the PUT method work fine

@BharatBhushan1610 Although that would work, the issue was to eliminate the need to explicitly assign the id value.

Was this page helpful?
0 / 5 - 0 ratings