问题
I know we have it in Java driver using cursor.getServerAddress(). However, I couldn't find any relevant call in C#.
回答1:
Unfortunately, after digging a little deeper though through the C# driver source code (and the Java source code to see what it was doing), the actual server address that was used as part of the fetch is hidden away in the Enumerator as a private member (_serverInstance
).
In particular, it's hidden away in a class called the MongoCursorEnumerator
. Unfortunately, there isn't an "honest" way of getting to it. You could use .NET reflection I suppose to get to it, but that's generally not a good idea, especially with code you don't own. If you wanted to have a custom fork of the driver, you could easily add it as a new property. You might want to add an issue here.
In general, you can get the instances used by the MongoDB connection, as they are available on the MongoServerInstance
class, the Address
property.
var client = new MongoClient();
var server = client.GetServer();
// server.Instance.Address
Documentation
However, in your case you can also get it from the cursor
via the Server
property:
cursor.Server.Instance.Address.Host
or
cursor.Server.Instances[]
Cursor Server Documentation
The C# driver interestingly throws and exception when more than one Instance is available. So, if you don't know how many instances there are, you either need to handle the exception
(InvalidOperationException
), or always use the Instances[]
property to return the associated instances.
来源:https://stackoverflow.com/questions/15886784/how-to-get-the-server-address-of-the-server-that-data-is-pulled-from