【问题标题】:Dot Net Core 3.1 - Unable to implement Mongo Atlas healthcheckDotnet Core 3.1 - 无法实现 Mongodb Atlas 健康检查
【发布时间】:2020-08-28 12:11:27
【问题描述】:

我无法使用 AspNetCore.HealthChecks.MongoDb nuget 包在 dot net core 3.1 中添加 Mongo Atlas 健康检查。将以下代码添加到 startup.cs 中

services.AddHealthChecks().AddMongoDb("MongoDbContext");

endpoints.MapHealthChecks("/api/v1.0/health", new HealthCheckOptions()

当我点击健康 URL 时,它给出了如下异常

"Status": "Unhealthy",
    "Description": null,
    "Exception": "MongoDB.Driver.MongoCommandException: Command listCollections failed: not authorized on test to execute command

【问题讨论】:

    标签: c# mongodb .net-core mongodb-atlas health-check


    【解决方案1】:

    当您完成所有配置后,您应该首先尝试添加 MongoDB 的健康检查定义:

    public void ConfigureServices (IServiceCollection services) {
        services.AddControllers ();
    
        string mongoDBConnection = Configuration.GetValue ("mongoDB:connection");
    
        services.AddHealthChecks ()
            .AddMongoDb (mongodbConnectionString: mongoDBConnection,
                name: "todo-db-check",
                failureStatus : HealthStatus.Unhealthy,
                tags : new string[] { "todo-api", "mongodb" });
    }
    

    您还需要在应用设置文件中添加 MongoDB 的连接字符串信息。

    "mongoDB:connection": "mongodb://localhost:27017"
    

    然后,将带有“/hc”路径的健康检查添加到请求管道。

    app.UseEndpoints (endpoints => {
        endpoints.MapControllers ();
        endpoints.MapHealthChecks ("/hc");
    });
    

    现在您可以运行 API 并通过浏览器点击“/hc”端点,它的数据库应该处于健康状态。

    您还可以查看 MongoDB (https://docs.mongodb.com/manual/) 的文档,对于该特定问题,您应该查看这些页面,以使其更清晰。

    (https://rmauro.dev/adding-health-checks-to-net-core-application/)

    (https://www.gokhan-gokalp.com/en/aspnet-core-series-06-monitor-the-health-of-your-applications-by-implementing-health-checks-and-azure-application-insights/)

    【讨论】:

    • 我已经有了这个实现,它与 mongo DB 运行状况检查配合得很好。我在使用 Mongo Atlas 健康检查时遇到问题。
    【解决方案2】:

    看github上的源码

    if (!string.IsNullOrEmpty(_specifiedDatabase))
    {
        // some users can't list all databases depending on database privileges, with
        // this you can list only collections on specified database.
        // Related with issue #43
    
        using var cursor = await mongoClient
            .GetDatabase(_specifiedDatabase)
            .ListCollectionNamesAsync(cancellationToken: cancellationToken);
        await cursor.FirstAsync(cancellationToken);
    }
    

    问题似乎是您在 Atlas 中没有足够的权限来列出数据库“test”中的集合

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 2021-11-18
      • 1970-01-01
      • 2018-06-05
      • 2021-10-23
      • 1970-01-01
      相关资源
      最近更新 更多