2017-12-31 186 views
0

MongoDB .NET API를 사용하여 MongoDB 데이터베이스에 연결하려고합니다. 그것은 잘 작동하고 자격 증명없이 localhost에 문서를 작성할 수 있지만 자격 증명을 사용하여 MongoDB Atlas 서버에 연결하려고하면 문서를 쓰려고 할 때 예외가 발생합니다. ?Atlas 서버에 문서를 쓸 때 C# MongoDB 예외가 발생했습니다.

Client = new MongoClient($"mongodb://{txtUsername.Text}:{txtPassword.Password}@{txtServer.Text}:{txtPort.Text}/{txtAuthDatabase.Text}"); 
var collection = Client.GetDatabase("TestDatabase").GetCollection<BsonDocument>("TestCollection"); 
var document = new BsonDocument { { "testKey", "testValue" } }; 
collection.InsertOne(document); //Exception here 

나는 또한 연결 문자열에 = replicaSet 연결 추가 시도했지만 아무것도를 할 것 같지 않습니다

예외는

System.TimeoutException 
    HResult=0x80131505 
    Message=A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/achille-shard-00-00-mdhfu.mongodb.net:27017" }", EndPoint: "Unspecified/achille-shard-00-00-mdhfu.mongodb.net:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "System.InvalidOperationException: Invalid BinaryConnection state transition from 4 to Failed. 
    at MongoDB.Driver.Core.Connections.BinaryConnection.OpenConnectionHelper.FailedOpeningConnection(Exception wrappedException) 
    at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext() 
--- End of stack trace from previous location where exception was thrown --- 
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 
    at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) 
    at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()" }] }. 
    Source=MongoDB.Driver.Core 
    StackTrace: 
    at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description) 
    at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask) 
    at MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken) 
    at MongoDB.Driver.Core.Clusters.Cluster.SelectServer(IServerSelector selector, CancellationToken cancellationToken) 
    at MongoDB.Driver.MongoClient.AreSessionsSupportedAfterServerSelection(CancellationToken cancellationToken) 
    at MongoDB.Driver.MongoClient.AreSessionsSupported(CancellationToken cancellationToken) 
    at MongoDB.Driver.OperationExecutor.StartImplicitSession(CancellationToken cancellationToken) 
    at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken) 
    at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken) 
    at MongoDB.Driver.MongoCollectionBase`1.<>c__DisplayClass58_0.<InsertOne>b__0(IEnumerable`1 requests, BulkWriteOptions bulkWriteOptions) 
    at MongoDB.Driver.MongoCollectionBase`1.InsertOne(TDocument document, InsertOneOptions options, Action`2 bulkWrite) 
    at MongoDB.Driver.MongoCollectionBase`1.InsertOne(TDocument document, InsertOneOptions options, CancellationToken cancellationToken) 
    at Gestione_Fatture_Casa_Di_Riposo.MainWindow.btnConnect_Click(Object sender, RoutedEventArgs e) in C:\Users\achil\source\repos\Gestione Fatture Casa Di Riposo\Gestione Fatture Casa Di Riposo\MainWindow.xaml.cs:line 46 
    at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) 
    at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 
    at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) 
    at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e) 
    at System.Windows.Controls.Primitives.ButtonBase.OnClick() 
    at System.Windows.Controls.Button.OnClick() 
    at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) 
    at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e) 
    at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) 
    at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) 
    at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) 
    at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 
    at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) 
    at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e) 
    at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) 
    at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) 
    at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) 
    at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 
    at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) 
    at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) 
    at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) 
    at System.Windows.Input.InputManager.ProcessStagingArea() 
    at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) 
    at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) 
    at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) 
    at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
    at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
    at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
    at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 
    at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
    at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) 
    at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) 
    at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 
    at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 
    at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 
    at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) 
    at System.Windows.Application.RunDispatcher(Object ignore) 
    at System.Windows.Application.RunInternal(Window window) 
    at System.Windows.Application.Run(Window window) 
    at System.Windows.Application.Run() 
    at Gestione_Fatture_Casa_Di_Riposo.App.Main() 

답변

1

이 연결 문자열이 형식을 시도입니다 :

mongodb://[username]:[password]@[host]:[port],[host]:[port],,[host]:[port]/test?ssl=[bool]&replicaSet=[replicasetName]&authSource=[authdbname] 

위의 예에서 가정 한 호스트의 수를 반영하여이 값을 변경하십시오. 귀하의 복제본에 3이 있습니다 ..

Atlas에서 직접 연결 문자열을 가져올 수 있어야합니다. 나는 이것을했고 이것은 복제본에있는 내 샌드 박스에 대한 형식입니다.

+0

대단히 감사합니다. 이것은 완벽하게 작동했습니다. D –