I have the following Method in service class
public async Task<bool> CreatePostAsync(Post postToCreate)
{
await _posts.InsertOneAsync(postToCreate);
var result = await _posts.FindAsync(post => post.Id == postToCreate.Id);
return await result.FirstOrDefaultAsync() != null;
}
And call it in controller class
[HttpPost(ApiRoutes.Posts.Create)]
public async Task<IActionResult> Create([FromBody] CreatePostRequest postRequest)
{
var post = new Post
{
Name = postRequest.Name,
Id = Guid.NewGuid().ToString()
};
if (!await _postService.CreatePostAsync(post))
return BadRequest();
var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}";
var locationUri = baseUrl + "/" + ApiRoutes.Posts.Get.Replace("{postId}", post.Id.ToString());
var response = new PostResponse {Id = post.Id };
return Created(locationUri, response);
}
When I call the API, I get a 500 error without any exception. The application continues to run. When debugging I noticed that the function exits at the InsertOneAsync line and the following lines are not reached.
When I do it this way ,with InsertOne, it works:
public async Task<bool> CreatePostAsync(Post postToCreate)
{
_posts.InsertOne(postToCreate);
var result = await _posts.FindAsync(post => post.Id == postToCreate.Id);
return await result.FirstOrDefaultAsync() != null;
}
does anyone see the reason for this? And is it dangerous if I use the method without async? (I am a beginner and not yet so knowledgeable in the subject)
For all other methods I use only the async versions
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…