Ad

C# 500 Internal Server Error MongoDB

- 1 answer

I've been trying to develop some api controller in ASP.NET that comunicates with mongoDB. In same controller I have few post/get methods, and they are working just fine. When I want to update collection in mongoDB, i call post method and when debbuging, all fields in that method are filled, but in return i get 500 error. Any idea where is the problem? The code that I use is:

JavaScript

comment.id += id;
comment.comment += test;
var newCommentUrl = 'api/PostInfo/' + comment;
postDataToDatabase(comment, newCommentUrl);

function postDataToDatabase(data, url) {
$.ajax({
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    url: url,
    type: 'POST',
    contentType: 'application/json;',
    data: JSON.stringify(data),
    success: function (valid) {
        if (valid) {
        } else {
        }
    }
});

ASP.NET Controller Method

        [HttpPost]
    [Route("api/PostInfo/{Comment}")]
    public async void Post(Comment comment)
    {
        BsonObjectId oldId = new BsonObjectId(new ObjectId(comment.id.ToString()));

        var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
        var mongoDbServer = mongoDbClient.GetDatabase("nmbp");
        var collection = mongoDbServer.GetCollection<PostInfo>("post");

        var filter = Builders<PostInfo>.Filter.Eq(e => e._id, oldId);
        var update = Builders<PostInfo>.Update.Push("post_comments", comment.comment);
        await collection.FindOneAndUpdateAsync(filter, update);
    }

It looks like method is called, but for some reason it returns 500.

Ad

Answer

If you are using async await pattern in your code, you must always as a best practice return a Task object when the method returns a void i.e. does not return any object.

In your situation, you need to use the following action method that is returning a Task object rather than the original one in which a void was being returned.

[HttpPost]
[Route("api/PostInfo/{Comment}")]
public async Task Post(Comment comment)
{
    BsonObjectId oldId = new BsonObjectId(new ObjectId(comment.id.ToString()));

    var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
    var mongoDbServer = mongoDbClient.GetDatabase("nmbp");
    var collection = mongoDbServer.GetCollection<PostInfo>("post");

    var filter = Builders<PostInfo>.Filter.Eq(e => e._id, oldId);
    var update = Builders<PostInfo>.Update.Push("post_comments", comment.comment);
    await collection.FindOneAndUpdateAs collection.FindOneAndUpdateAsync(filter, update);
}

This is according to Microsoft documentation at this URL: Async Await Best Practice

In the following example, async method Task_MethodAsync doesn't contain a return statement. Therefore, you specify a return type of Task for the method, which enables Task_MethodAsync to be awaited. The definition of the Task type doesn't include a Result property to store a return value.

A code sample from above documentation illustrating this best practice is as given below.

    // TASK EXAMPLE
async Task Task_MethodAsync()
{
    // The body of an async method is expected to contain an awaited 
    // asynchronous call.
    // Task.Delay is a placeholder for actual work.
    await Task.Delay(2000);
    // Task.Delay delays the following line by two seconds.
    textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");

    // This method has no return statement, so its return type is Task.  
}
Ad
source: stackoverflow.com
Ad