Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

c# - ASP.Net Core MongoDB.Driver InsertOneAsync doesnt work

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...