C#500内部服务器错误MongoDB
本文关键字:MongoDB 错误 服务器 内部 C#500 | 更新日期: 2023-09-27 18:29:50
我一直在尝试在ASP.NET中开发一些与mongoDB通信的api控制器。在同一个控制器中,我有一些post/get方法,它们运行得很好。当我想更新mongoDB中的集合时,我调用post方法,当debbuging时,该方法中的所有字段都被填充,但作为回报,我得到了500个错误。知道问题出在哪里吗?我使用的代码是:
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控制器方法
[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);
}
看起来方法被调用了,但由于某种原因,它返回500。
如果在代码中使用async await
模式,则在方法返回void(即不返回任何对象)时,作为最佳实践,必须始终返回Task
对象。
在您的情况下,您需要使用以下操作方法来返回Task
对象,而不是返回void
的原始对象。
[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.FindOneAndUpdateAsync(filter, update);
}
这是根据以下URL的Microsoft文档:Async Await最佳实践
在以下示例中,异步方法Task_MethodAsync不包含返回语句。因此,您可以为该方法指定Task的返回类型,这样就可以等待Task_MethodAsync。Task类型的定义不包括用于存储返回值的Result属性。
上面文档中的代码示例说明了这种最佳实践,如下所示。
// 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.
}