Docs Menu
Docs Home
/ / /
C#/.NET

Connection Troubleshooting

On this page

  • Connection Error
  • Check Your Connection String
  • Configure Your Firewall
  • Authentication Error
  • Check Your Connection String
  • Verify the MongoClientSettings Properties
  • Verify the User Is in the Authentication Database
  • X.509 Credential Error
  • Create and Store the Certificate On-Disk
  • Error Sending Message
  • Check the User Permissions
  • Configure Your Firewall
  • Check the Number of Connections
  • Too Many Open Connections
  • Check the Number of Connections
  • Timeout Error
  • Set connectTimeoutMS
  • Check the Number of Connections

This page offers potential solutions to issues you might encounter when using the MongoDB .NET/C# Driver to connect to a MongoDB deployment.

Note

This page addresses only connection issues. If you encounter any other issues with MongoDB or the driver, visit the following resources:

  • The Frequently Asked Questions (FAQ) for the .NET/C# Driver

  • The Issues & Help page, which has information about reporting bugs, contributing to the driver, and finding additional resources

  • The MongoDB Community Forums for questions, discussions, or general technical support

The following error message indicates that the driver cannot connect to a server on the specified hostname or port. Multiple situations can generate this error message. In this sample error message, the hostname is 127.0.0.1 and the port is 27017:

Error: couldn't connect to server 127.0.0.1:27017

The following sections describe actions you can take to potentially resolve the issue.

Verify that the hostname and port number in the connection string are both accurate. The default port value for a MongoDB instance is 27017, but you can configure MongoDB to communicate on another port.

Verify that the ports your MongoDB deployment listens on are not blocked by a firewall on the same network. MongoDB uses port 27017 by default. To learn more about the default ports MongoDB uses and how to change them, see Default MongoDB Port.

Warning

Do not open a port in your firewall unless you are sure it's the port used by your MongoDB deployment.

The .NET/C# Driver can fail to connect to a MongoDB instance if the authentication mechanism is not configured correctly. If you are using SCRAM-SHA-256 or SCRAM-SHA-1 for authentication and the driver fails to connect, the driver might raise an error message similar to one of the following messages:

Command failed with error 18 (AuthenticationFailed): 'Authentication
failed.' on server <hostname>:<port>.
Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","principalName":
"<db_username>","<auth database>":"<db_username>","client":"127.0.0.1:2012",
"result":"UserNotFound: Could not find user}}
connection() error occurred during connection handshake: auth error:
sasl conversation error: unable to authenticate using mechanism
"SCRAM-SHA-256": (AuthenticationFailed) Authentication failed.

The following sections describe actions you can take to potentially resolve the issue.

An invalid connection string is the most common cause of authentication issues when attempting to connect to MongoDB using connection strings and SCRAM-SHA-256 or SCRAM-SHA-1.

Tip

For more information about connection strings, see Connection URI in the Connection Guide.

If your connection string contains a username and password, ensure that they are in the correct format. If the username or password includes any of the following characters, they must be percent encoded:

: / ? # [ ] @

The following example shows how to percent encode "#MyPassword?":

Console.WriteLine(System.Web.HttpUtility.UrlEncode("#MyPassword?"));

This results in the following output:

%23MyPassword%3F

You can use a MongoClientSettings object to configure the settings when attempting to connect to a MongoDB deployment. You can use the Credential property to set authentication information. If the credential information is not correct, you will receive authentication errors when you attempt to connect to your MongoDB deployment.

To successfully authenticate a connection by using a username and password with SCRAM-SHA-256 or SCRAM-SHA-1, the username must be defined in the authentication database. The default authentication database is the admin database. To use a different database for authentication, specify the authSource option in the connection string. The following example instructs the driver to use users as the authentication database:

using MongoDB.Driver;
// Connection URI
const string connectionUri = "mongodb://<db_username>:<db_password>@<hostname>:<port>/?authSource=users";
// Create a new client and connect to the server
var client = new MongoClient(connectionUri);

You can also set configuration settings by creating a MongoClientSettings object and passing that to the MongoClient constructor. You can use the Credential property to set the login credentials including specifying the authentication database. For more information about using MongoClientSettings as well as some examples, see Using MongoClientSettings.

You can check if this is the issue by attempting to connect to a MongoDB instance hosted on the local machine with the same code. A deployment on the same machine doesn't require any authorization to connect.

If you are using Windows as your operating system, you might encounter an issue in which the .NET/C# Driver is unable to locate an X.509 authentication certificate in memory. This error is raised with the following error message:

No credentials are available in the security package

The following section describes a method that may help resolve the issue.

Use the following code to generate any X.509 certificates required by your application:

using (X509Certificate2 certWithKey = certOnly.CopyWithPrivateKey(key))
{
return new X509Certificate2(certWithKey.Export(X509ContentType.Pkcs12));
}

When the driver fails to send a command after you make a request, it may display the following error message:

com.mongodb.MongoSocketWriteException: Exception sending message

The following sections describe actions you can take to potentially resolve the issue.

Verify that you've accessed the MongoDB deployment with the correct user. The term "message" in the error can be a command sent by the driver. If you are using a user that doesn't have permissions to send the command, the driver could generate this error.

Also ensure that the user has the appropriate permissions for the message you are sending. MongoDB uses Role-Based Access Control (RBAC) to control access to a MongoDB deployment. For more information about how to configure RBAC in MongoDB, see Role-Based Access Control.

The firewall needs to have an open port for communicating with the MongoDB instance. For more information about configuring the firewall, see Configure Your Firewall in the Connection Error section.

Each MongoClient instance supports a maximum number of concurrent open connections in its connection pool. You can configure the parameter MaxConnectionPoolSize which defines this limit. The default value is 100. If there are already a number of open connections equal to MaxConnectionPoolSize, the server waits until a connection becomes available. If this wait time exceeds the MaxConnectionIdleTime value, the driver responds with an error.

For more information about how connection pooling works, see How Does Connection Pooling Work in the .NET/C# Driver? in the FAQ.

The driver creates the following error message when it attempts to open a connection, but it's reached the maximum number of connections:

connection refused because too many open connections

The following section describes a method that may help resolve the issue.

If you need to create more open connections, increase MaxConnectionPoolSize. For more information about checking the number of connections, see Check the Number of Connections in the Error Sending Message section.

When the network is not able to deliver a request from the driver to the server quickly enough, it can time out. When this happens, you might receive an error message similar to the following message:

timed out while checking out a connection from connection pool: context canceled

If you receive this error, try the following action to resolve the issue.

The driver may hang when it's unable to establish a connection because the driver takes too long attempting to reach unreachable replica set nodes. You can limit the time the driver spends attempting to establish the connection by using the connectTimeMS setting. To learn more about this setting, see the Timeout Options in the Server manual.

You should ensure the connectTimeoutMS setting is not lower than the highest network latency you have to a member of the set. If one of the secondary members has a latency of 10000 milliseconds, setting the connectTimeoutMS to 9000 prevents the driver from ever connecting to that member.

You can set this option on the connection string. The following example sets connectTimeoutMS to 10000 milliseconds.

using MongoDB.Driver;
// Connection URI
const string connectionUri = "mongodb://<db_username>:<db_password>@<hostname>:<port>/?connectTimeoutMS=10000";
// Create a new client and connect to the server
var client = new MongoClient(connectionUri);

You can also set configuration settings by creating a MongoClientSettings object and passing that to the MongoClient constructor. For more information about using MongoClientSettings as well as some examples, see Using MongoClientSettings.

The number of connections to the server may exceed MaxConnectionPoolSize. For more information about checking the number of connections, see Check the Number of Connections in the Error Sending Message section.

Back

FAQ