How to fix SQL Exception happening only in android? - c#

I'm using xamarin forms to develop a cross-platform app.
As part of my app, I have a login page where the user enters his credentials and gets authenticated.
I'm using entity framework core and I'm connecting to a SQL server which is hosted on Azures cloud.
The code works and I can log in successfully, but only with IOS and UWP, if i try with Android I receive this exception:
System.Data.SqlClient.SqlException: <Timeout exceeded getting exception details>
If I continue the debugging I receive another exception which is:
System.Data.SqlClient.SqlException: Snix_PreLogin (provider: SNI_PN6, error: 31 - SNI_ERROR_31) Snix_PreLogin (provider: SNI_PN6, error: 31 - SNI_ERROR_31)
This is my Icommand:
LoginCommand = new Command(async () => await Login());
this is my method inside the view-model:
private async Task Login()
{
IsBusy = true;
if (String.IsNullOrWhiteSpace(_emailField) || String.IsNullOrWhiteSpace(_passwordField))
await App.Current.MainPage.DisplayAlert("Error", "All fields must contain values.", "Ok");
else
{
if (await DatabaseHandler.LoginUser(_emailField, _passwordField))
{
App.CurrentAccount = new UserAccount { Email = _emailField, Password = _passwordField };
App.Current.MainPage = new MainPage();
}
else
await App.Current.MainPage.DisplayAlert("Error", "Email or password are incorrect.", "Ok");
}
IsBusy = false;
}
and this is my method inside the DatabaseHandler:
public static async Task<bool> LoginUser(string email, string password)
{
AzureContext AzureDb = new AzureContext();
App.CurrentAccount = await AzureDb.UserAccounts.SingleOrDefaultAsync(account => account.Email == email && account.Password == password);
return (App.CurrentAccount == null) ? false : true;
}
Another thing worth mentioning is that when I comment out the IsBusy lines in the Login method which are responsible for the activity indicator, I no longer get an exception.
But, it's still not working, instead of an exception the UI just freezes for a long time and after it unfreezes nothing happens.
Help would be appreciated.
EDIT:
After playing around a little with the exception handling the full exception i get is this:
{System.Data.SqlClient.SqlException (0x80131904): Snix_PreLogin (provider: SNI_PN6, error: 31 - SNI_ERROR_31)Snix_PreLogin (provider: SNI_PN6, error: 31 - SNI_ERROR_31) ---> System.AggregateException: One or more errors occurred. (Authentication failed, see inner exception.)
---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> System.AggregateException: One or more errors occurred. (Unable to write data to the transport connection: Connection reset by peer.)
---> System.IO.IOException: Unable to write data to the transport connection: Connection reset by peer. ---> System.Net.Sockets.SocketException: Connection reset by peer at System.Net.Sockets.Socket.Send (System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags) [0x00016] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x0009b] in <634e1667c20e48cfb6aa884228f8db67>:0 --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x000e2] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Data.SqlClient.SNI.SslOverTdsStream.WriteInternal (System.Byte[] buffer, System.Int32 offset, System.Int32 count, System.Threading.CancellationToken token, System.Boolean async) [0x0017b] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Wait () [0x00000] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Data.SqlClient.SNI.SslOverTdsStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 count) [0x0000f] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at Mono.Net.Security.MobileAuthenticatedStream.<InnerWrite>b__86_0 () [0x00006] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Threading.Tasks.Task.InnerInvoke () [0x0000f] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Execute () [0x00000] in <84c6975c2cbc47b489a2a76477d7a312>:0 --- End of stack trace from previous location where exception was thrown --- at Mono.Net.Security.MobileAuthenticatedStream.InnerWrite (System.Boolean sync, System.Threading.CancellationToken cancellationToken) [0x000d3] in <634e1667c20e48cfb6aa884228f8db67>:0 at Mono.Net.Security.AsyncProtocolRequest.ProcessOperation (System.Threading.CancellationToken cancellationToken) [0x00196] in <634e1667c20e48cfb6aa884228f8db67>:0 at Mono.Net.Security.AsyncProtocolRequest.StartOperation (System.Threading.CancellationToken cancellationToken) [0x0008b] in <634e1667c20e48cfb6aa884228f8db67>:0 --- End of inner exception stack trace --- at Mono.Net.Security.MobileAuthenticatedStream.ProcessAuthentication (System.Boolean runSynchronously, Mono.Net.Security.MonoSslAuthenticationOptions options, System.Threading.CancellationToken cancellationToken) [0x00252] in <634e1667c20e48cfb6aa884228f8db67>:0 --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Wait () [0x00000] in <84c6975c2cbc47b489a2a76477d7a312>:0 at Mono.Net.Security.MobileAuthenticatedStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) [0x0003d] in <634e1667c20e48cfb6aa884228f8db67>:0 at (wrapper remoting-invoke-with-check) Mono.Net.Security.MobileAuthenticatedStream.AuthenticateAsClient(string,System.Security.Cryptography.X509Certificates.X509CertificateCollection,System.Security.Authentication.SslProtocols,bool) at Mono.Net.Security.MobileAuthenticatedStream.AuthenticateAsClient (System.String targetHost) [0x00007] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Net.Security.SslStream.AuthenticateAsClient (System.String targetHost) [0x00006] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Data.SqlClient.SNI.SNITCPHandle.EnableSsl (System.UInt32 options) [0x0000c] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at System.Data.SqlClient.SNI.SNIProxy.EnableSsl (System.Data.SqlClient.SNI.SNIHandle handle, System.UInt32 options) [0x00000] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 ---> (Inner Exception #0) System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception. ---> System.AggregateException: One or more errors occurred. (Unable to write data to the transport connection: Connection reset by peer.)
---> System.IO.IOException: Unable to write data to the transport connection: Connection reset by peer. ---> System.Net.Sockets.SocketException: Connection reset by peer at System.Net.Sockets.Socket.Send (System.Byte[] buffer, System.Int32 offset, System.Int32 size, System.Net.Sockets.SocketFlags socketFlags) [0x00016] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x0009b] in <634e1667c20e48cfb6aa884228f8db67>:0 --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x000e2] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Data.SqlClient.SNI.SslOverTdsStream.WriteInternal (System.Byte[] buffer, System.Int32 offset, System.Int32 count, System.Threading.CancellationToken token, System.Boolean async) [0x0017b] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 --- End of inner exception stack trace --- at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Wait () [0x00000] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Data.SqlClient.SNI.SslOverTdsStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 count) [0x0000f] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at Mono.Net.Security.MobileAuthenticatedStream.<InnerWrite>b__86_0 () [0x00006] in <634e1667c20e48cfb6aa884228f8db67>:0 at System.Threading.Tasks.Task.InnerInvoke () [0x0000f] in <84c6975c2cbc47b489a2a76477d7a312>:0 at System.Threading.Tasks.Task.Execute () [0x00000] in <84c6975c2cbc47b489a2a76477d7a312>:0 --- End of stack trace from previous location where exception was thrown --- at Mono.Net.Security.MobileAuthenticatedStream.InnerWrite (System.Boolean sync, System.Threading.CancellationToken cancellationToken) [0x000d3] in <634e1667c20e48cfb6aa884228f8db67>:0 at Mono.Net.Security.AsyncProtocolRequest.ProcessOperation (System.Threading.CancellationToken cancellationToken) [0x00196] in <634e1667c20e48cfb6aa884228f8db67>:0 at Mono.Net.Security.AsyncProtocolRequest.StartOperation (System.Threading.CancellationToken cancellationToken) [0x0008b] in <634e1667c20e48cfb6aa884228f8db67>:0 --- End of inner exception stack trace --- at Mono.Net.Security.MobileAuthenticatedStream.ProcessAuthentication (System.Boolean runSynchronously, Mono.Net.Security.MonoSslAuthenticationOptions options, System.Threading.CancellationToken cancellationToken) [0x00252] in <634e1667c20e48cfb6aa884228f8db67>:0 <--- at System.Data.SqlClient.SqlInternalConnectionTds..ctor (System.Data.ProviderBase.DbConnectionPoolIdentity identity, System.Data.SqlClient.SqlConnectionString connectionOptions, System.Data.SqlClient.SqlCredential credential, System.Object providerInfo, System.String newPassword, System.Security.SecureString newSecurePassword, System.Boolean redirectedUserInstance, System.Data.SqlClient.SqlConnectionString userConnectionOptions, System.Data.SqlClient.SessionData reconnectSessionData, System.Boolean applyTransientFaultHandling) [0x00163] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at System.Data.SqlClient.SqlConnectionFactory.CreateConnection (System.Data.Common.DbConnectionOptions options, System.Data.Common.DbConnectionPoolKey poolKey, System.Object poolGroupProviderInfo, System.Data.ProviderBase.DbConnectionPool pool, System.Data.Common.DbConnection owningConnection, System.Data.Common.DbConnectionOptions userOptions) [0x00144] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection (System.Data.ProviderBase.DbConnectionPool pool, System.Data.Common.DbConnection owningObject, System.Data.Common.DbConnectionOptions options, System.Data.Common.DbConnectionPoolKey poolKey, System.Data.Common.DbConnectionOptions userOptions) [0x0000c] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at System.Data.ProviderBase.DbConnectionPool.CreateObject (System.Data.Common.DbConnection owningObject, System.Data.Common.DbConnectionOptions userOptions, System.Data.ProviderBase.DbConnectionInternal oldConnection) [0x00184] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest (System.Data.Common.DbConnection owningObject, System.Data.Common.DbConnectionOptions userOptions, System.Data.ProviderBase.DbConnectionInternal oldConnection) [0x00040] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at System.Data.ProviderBase.DbConnectionPool.TryGetConnection (System.Data.Common.DbConnection owningObject, System.UInt32 waitForMultipleObjectsTimeout, System.Boolean allowCreate, System.Boolean onlyOneCheckConnection, System.Data.Common.DbConnectionOptions userOptions, System.Data.ProviderBase.DbConnectionInternal& connection) [0x000a4] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 at System.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen () [0x00092] in <fb2d0bc6c8f7446eaa3eaa0ac572f8d3>:0 --- End of stack trace from previous location where exception was thrown --- at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync (System.Boolean errorsExpected, System.Threading.CancellationToken cancellationToken) [0x000f9] in <c486d2adb419411a9a11f423095801e5>:0 at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync (System.Threading.CancellationToken cancellationToken, System.Boolean errorsExpected) [0x0009b] in <c486d2adb419411a9a11f423095801e5>:0 at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1+AsyncEnumerator[T].BufferlessMoveNext (Microsoft.EntityFrameworkCore.DbContext _, System.Boolean buffer, System.Threading.CancellationToken cancellationToken) [0x00098] in <c486d2adb419411a9a11f423095801e5>:0 at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult] (TState state, System.Func`4[T1,T2,T3,TResult] operation, System.Func`4[T1,T2,T3,TResult] verifySucceeded, System.Threading.CancellationToken cancellationToken) [0x00089] in <70780d57b1e644f080d08b633fa994bf>:0 at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable`1+AsyncEnumerator[T].MoveNext (System.Threading.CancellationToken cancellationToken) [0x00135] in <c486d2adb419411a9a11f423095801e5>:0 at System.Linq.AsyncEnumerable.SingleOrDefault_[TSource] (System.Collections.Generic.IAsyncEnumerable`1[T] source, System.Threading.CancellationToken cancellationToken) [0x000d7] in <afef21b57ad6402f8df4c5299ba699e2>:0 at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+TaskResultAsyncEnumerable`1+Enumerator[T].MoveNext (System.Threading.CancellationToken cancellationToken) [0x00075] in <e66a1f96e9734a7fac7cea0901022728>:0 at System.Linq.AsyncEnumerable+SelectEnumerableAsyncIterator`2[TSource,TResult].MoveNextCore (System.Threading.CancellationToken cancellationToken) [0x000a6] in <afef21b57ad6402f8df4c5299ba699e2>:0 at System.Linq.AsyncEnumerable+AsyncIterator`1[TSource].MoveNext (System.Threading.CancellationToken cancellationToken) [0x00101] in <afef21b57ad6402f8df4c5299ba699e2>:0 at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+ExceptionInterceptor`1+EnumeratorExceptionInterceptor[T].MoveNext (System.Threading.CancellationToken cancellationToken) [0x00143] in <e66a1f96e9734a7fac7cea0901022728>:0 at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteSingletonAsyncQuery[TResult] (Microsoft.EntityFrameworkCore.Query.QueryContext queryContext, System.Func`2[T,TResult] compiledQuery, Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger`1[TLoggerCategory] logger, System.Type contextType) [0x000d6] in <e66a1f96e9734a7fac7cea0901022728>:0 at Life_Programmer.Services.DatabaseServices.DatabaseHandler.LoginUser (System.String email, System.String password) [0x00108] in C:\Users\Meydan\source\repos\Life_Programmer\Life_Programmer\Life_Programmer\Services\DatabaseServices\DatabaseHandler.cs:43 ClientConnectionId:7453d528-808d-4249-b0db-ee7d31c86008}
EDIT2:
If I handle the exception so the application won't crash, then after the first try it works as expected.
So the problem occurs only on the first login try, and only with Android.

I changed the way my app communicates with the database and the problem got solved, instead of communicating from my app directly to the database I'm communicating to it through a web API.

Related

Error in Connection to MySQL with a publish App of C# .NETCore 5.0

I have an application that connects in MySql server of my own database register and log in users, when i run it from IDE works fine but when i exports the app to publish it throws an EntityframeworkCore error, this package is not even installed, i have disabled the firewall and change the appsettings.json to all configurations as possible, i don't know what i'm missing here
here is the error when i do a POST in the exported app
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'usuariodb' on server 'localhost'.
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'UsuarioApi.Data.UserDbContext'.
System.TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
---> System.TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.
---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize
---> System.NotSupportedException: CodeBase is not supported on assemblies loaded from a single-file bundle.
at System.Reflection.RuntimeAssembly.get_CodeBase()
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.get_ConfigPaths()
at System.Configuration.ClientConfigurationHost.GetStreamName(String configPath)
at System.Configuration.ClientConfigurationHost.get_IsAppConfigHttp()
at System.Configuration.Internal.DelegatingConfigHost.get_IsAppConfigHttp()
at System.Configuration.ClientConfigurationSystem..ctor()
at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
--- End of inner exception stack trace ---
at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at MySql.Data.MySqlClient.MySqlConfiguration..cctor()
--- End of inner exception stack trace ---
at MySql.Data.MySqlClient.MySqlConfiguration.get_Settings()
at MySql.Data.MySqlClient.Replication.ReplicationManager..cctor()
--- End of inner exception stack trace ---
at MySql.Data.MySqlClient.Replication.ReplicationManager.IsReplicationGroup(String groupName)
at MySql.Data.MySqlClient.MySqlConnection.Open()
at System.Data.Common.DbConnection.OpenAsync(CancellationToken cancellationToken)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
at MySql.EntityFrameworkCore.Storage.Internal.MySQLExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
System.TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
---> System.TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.
---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize
---> System.NotSupportedException: CodeBase is not supported on assemblies loaded from a single-file bundle.
at System.Reflection.RuntimeAssembly.get_CodeBase()
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.get_ConfigPaths()
at System.Configuration.ClientConfigurationHost.GetStreamName(String configPath)
at System.Configuration.ClientConfigurationHost.get_IsAppConfigHttp()
at System.Configuration.Internal.DelegatingConfigHost.get_IsAppConfigHttp()
at System.Configuration.ClientConfigurationSystem..ctor()
at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
--- End of inner exception stack trace ---
at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at MySql.Data.MySqlClient.MySqlConfiguration..cctor()
--- End of inner exception stack trace ---
at MySql.Data.MySqlClient.MySqlConfiguration.get_Settings()
at MySql.Data.MySqlClient.Replication.ReplicationManager..cctor()
--- End of inner exception stack trace ---
at MySql.Data.MySqlClient.Replication.ReplicationManager.IsReplicationGroup(String groupName)
at MySql.Data.MySqlClient.MySqlConnection.Open()
at System.Data.Common.DbConnection.OpenAsync(CancellationToken cancellationToken)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
at MySql.EntityFrameworkCore.Storage.Internal.MySQLExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMFBPG06USN4", Request id "0HMFBPG06USN4:00000001": An unhandled exception was thrown by the application.
System.AggregateException: One or more errors occurred. (The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.)
---> System.TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.Replication.ReplicationManager' threw an exception.
---> System.TypeInitializationException: The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.
---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize
---> System.NotSupportedException: CodeBase is not supported on assemblies loaded from a single-file bundle.
at System.Reflection.RuntimeAssembly.get_CodeBase()
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.get_ConfigPaths()
at System.Configuration.ClientConfigurationHost.GetStreamName(String configPath)
at System.Configuration.ClientConfigurationHost.get_IsAppConfigHttp()
at System.Configuration.Internal.DelegatingConfigHost.get_IsAppConfigHttp()
at System.Configuration.ClientConfigurationSystem..ctor()
at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
--- End of inner exception stack trace ---
at System.Configuration.ConfigurationManager.EnsureConfigurationSystem()
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at MySql.Data.MySqlClient.MySqlConfiguration..cctor()
--- End of inner exception stack trace ---
at MySql.Data.MySqlClient.MySqlConfiguration.get_Settings()
at MySql.Data.MySqlClient.Replication.ReplicationManager..cctor()
--- End of inner exception stack trace ---
at MySql.Data.MySqlClient.Replication.ReplicationManager.IsReplicationGroup(String groupName)
at MySql.Data.MySqlClient.MySqlConnection.Open()
at System.Data.Common.DbConnection.OpenAsync(CancellationToken cancellationToken)
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
at MySql.EntityFrameworkCore.Storage.Internal.MySQLExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Identity.UserManager`1.FindByNameAsync(String userName)
at Microsoft.AspNetCore.Identity.SignInManager`1.PasswordSignInAsync(String userName, String password, Boolean isPersistent, Boolean lockoutOnFailure)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at UsuarioApi.Services.LoginService.LogaUsuario(LoginRequest request)
at UsuarioApi.Controllers.LoginController.LogaUsuario(LoginRequest request)
at lambda_method1(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
Startup class
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var conString = Configuration.GetConnectionString("UsuarioConnection");
services.AddDbContext<UserDbContext>(options => options.UseMySQL(conString));
services.AddIdentity<IdentityUser<int>, IdentityRole<int>>(opt =>
{
opt.SignIn.RequireConfirmedEmail = true;
opt.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<UserDbContext>()
.AddDefaultTokenProviders();
services.AddControllers();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<CadastroService, CadastroService>();
services.AddScoped<LogoutService, LogoutService>();
services.AddScoped<LoginService, LoginService>();
services.AddScoped<TokenService, TokenService>();
services.AddScoped<EmailService, EmailService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Connection String
"ConnectionStrings": {
"UsuarioConnection": "server=localhost;port=3306;database=usuariodb;user=root;password=admin"
}

Getting this strange error when testing an api

for school we need to create an Android App with data from an api.
I was following this tutorial from school and everything went well.
But then I came at the testing part and I get this error everytime.
So here is the full error:
{Java.Net.UnknownHostException: Unable to resolve host "www.tronalddump.io": No address associated with hostname ---> Java.Lang.RuntimeException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
--- End of inner exception stack trace ---
at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <89755ea61d9c4ae0a40ce90b872c9e2d>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeAbstractVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00014] in <89755ea61d9c4ae0a40ce90b872c9e2d>:0
at Javax.Net.Ssl.HttpsURLConnectionInvoker.Connect () [0x0000a] in <2df86f44c8e946618f31cb3aed952f5b>:0
at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass44_0.<ConnectAsync>b__0 () [0x0007d] in <2df86f44c8e946618f31cb3aed952f5b>:0
at System.Threading.Tasks.Task.InnerInvoke () [0x0000f] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2476
at System.Threading.Tasks.Task.Execute () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2319
--- End of stack trace from previous location where exception was thrown ---
at Xamarin.Android.Net.AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState) [0x0012e] in <2df86f44c8e946618f31cb3aed952f5b>:0
at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x002d0] in <2df86f44c8e946618f31cb3aed952f5b>:0
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x000b3] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:531
at System.Net.Http.HttpClient.GetStringAsyncCore (System.Threading.Tasks.Task`1[TResult] getTask) [0x0002e] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:147
at TronaldDump.Repositories.TronaldDumpRepository.GetRandomQuoteAsync () [0x0004e] in C:\2020-2021-DEVPROG-PROJECT-StruyveMattice\TronaldDump\TronaldDump\Repositories\TronaldDumpRepository.cs:32
--- End of managed Java.Net.UnknownHostException stack trace ---
java.net.UnknownHostException: Unable to resolve host "www.tronalddump.io": No address associated with hostname
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:157)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
at java.net.InetAddress.getAllByName(InetAddress.java:1154)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:26)
Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Linux.android_getaddrinfo(Native Method)
at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:172)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:137)
... 15 more
}

ASP.Net Core 3 The remote certificate is invalid on MacOs

When I try to call an API method using identityserver4, I tried before on Windows and it is working fine only in Mac OS I faced this issue and I donĀ“t know what is happened and how to resolve it.
I can access to https://localhost:6001/.well-known/openid-configuration and I can login correctly, also I tried to run this command: dotnet dev-certs https --trust and run correctly but that is not fixing the issue.
This is the error in the terminal:
fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3] Exception occurred while processing message. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'System.String'. ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure. at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception) at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest) --- End of stack trace from previous location where exception was thrown --- at System.Net.Security.SslStream.ThrowIfExceptional() at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar) at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel) --- End of inner exception stack trace --- at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel) at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel) at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) --- End of inner exception stack trace --- at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. ---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'System.String'. ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure. at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception) at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest) --- End of stack trace from previous location where exception was thrown --- at System.Net.Security.SslStream.ThrowIfExceptional() at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) at System.Net.Security.SslStream.<>c.<AuthenticateAsClientAsync>b__65_1(IAsyncResult iar) at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel) --- End of inner exception stack trace --- at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel) at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel) at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) --- End of inner exception stack trace --- at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3] Exception occurred while processing message. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3] Exception occurred while processing message. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3] Exception occurred while processing message. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
my Startup.cs is :
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:6001";
options.RequireHttpsMetadata = false;
options.Audience = "myApiName";
});
Thanks.
Dotnet dev-certs don't work on Linux or Mac.
That is because the dev-tools issue an incorrect root certificate.
Windows apparently accepts incorrect root certificates...
What you need to do is this:
create a root certificate
add this to your machine's root certificate store
sign the SSL-certificate with that root
certificate.
Alternatively, you can just ignore SSL-errors:
if (hostingEnvironment.IsDevelopment())
{
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(sender, certificate, chain, sslPolicyErrors) => true;
}
Or you can write a more complex Validation-Callback, that just ignores untrusted root certificates:
/// <summary>
/// This is to take care of SSL certification validation which are not issued by Trusted Root CA.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="chain">The chain.</param>
/// <param name="sslPolicyErrors">The errors.</param>
/// <returns></returns>
/// <code></code>
public static bool RemoteCertValidate(object sender
, System.Security.Cryptography.X509Certificates.X509Certificate certificate
, System.Security.Cryptography.X509Certificates.X509Chain chain
, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// Logger.Current.Error("X509Certificate [{0}] Policy Error: '{1}'", certificate.Subject, sslPolicyErrors);
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else if (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NotTimeValid)
{
// Ignore Expired certificates
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
} // Next status
} // End if (chain != null && chain.ChainStatus != null)
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates (, or expired certificates).
// These certificates are valid for default Exchange server installations, so return true.
return true;
} // End if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
return false;
}
And add that to ServerCertificateValidationCallback:
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertValidate);
Your Mac does not trust the local development Windows certificate for localhost, you need to buy a get a real certificate that your Mac will trust. Perhaps use LetsEncrypt if you want a real trusted certificate for free.

Entity Framework Core SaveChanges causes error on Mac

I'm currently trying to build an EF core project, but when I call db.SaveChanges() I get the following error:
System.TypeInitializationException: The type initializer for 'Microsoft.Data.SqlClient.InOutOfProcHelper' threw an exception. ---> System.EntryPointNotFoundException: GetModuleHandle assembly:<unknown assembly> type:<unknown type> member:(null)
at (wrapper managed-to-native) Microsoft.Data.Common.SafeNativeMethods.GetModuleHandle(string)
at Microsoft.Data.SqlClient.InOutOfProcHelper..ctor () [0x00006] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at Microsoft.Data.SqlClient.InOutOfProcHelper..cctor () [0x00000] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
--- End of inner exception stack trace ---
at Microsoft.Data.SqlClient.SqlConnectionString..ctor (System.String connectionString) [0x0000d] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions (System.String connectionString, Microsoft.Data.Common.DbConnectionOptions previous) [0x00000] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at Microsoft.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup (Microsoft.Data.Common.DbConnectionPoolKey key, Microsoft.Data.ProviderBase.DbConnectionPoolGroupOptions poolOptions, Microsoft.Data.Common.DbConnectionOptions& userConnectionOptions) [0x0003e] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at Microsoft.Data.SqlClient.SqlConnection.ConnectionString_Set (Microsoft.Data.Common.DbConnectionPoolKey key) [0x00008] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at Microsoft.Data.SqlClient.SqlConnection.set_ConnectionString (System.String value) [0x0006b] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at Microsoft.Data.SqlClient.SqlConnection..ctor (System.String connectionString, Microsoft.Data.SqlClient.SqlCredential credential) [0x00006] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at Microsoft.Data.SqlClient.SqlConnection..ctor (System.String connectionString) [0x00000] in <a1c8e16fd44948ee8c6a463f125e71f0>:0
at (wrapper remoting-invoke-with-check) Microsoft.Data.SqlClient.SqlConnection..ctor(string)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection () [0x00006] in <5c775909c1cf40629fd2452310cf8cc1>:0
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection () [0x0000a] in <5314a29febc14288a1bc53bf7b46d725>:0
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateCommand (Microsoft.EntityFrameworkCore.Storage.RelationalCommandParameterObject parameterObject, System.Guid commandId, Microsoft.EntityFrameworkCore.Diagnostics.DbCommandMethod commandMethod) [0x0005c] in <5314a29febc14288a1bc53bf7b46d725>:0
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader (Microsoft.EntityFrameworkCore.Storage.RelationalCommandParameterObject parameterObject) [0x00027] in <5314a29febc14288a1bc53bf7b46d725>:0
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1+Enumerator[T].InitializeReader (Microsoft.EntityFrameworkCore.DbContext _, System.Boolean result) [0x00050] in <5314a29febc14288a1bc53bf7b46d725>:0
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult] (TState state, System.Func`3[T1,T2,TResult] operation, System.Func`3[T1,T2,TResult] verifySucceeded) [0x00011] in <5c775909c1cf40629fd2452310cf8cc1>:0
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1+Enumerator[T].MoveNext () [0x00193] in <5314a29febc14288a1bc53bf7b46d725>:0
at System.Linq.Enumerable.SingleOrDefault[TSource] (System.Collections.Generic.IEnumerable`1[T] source) [0x00041] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-10/external/bockbuild/builds/mono-x64/external/corefx/src/System.Linq/src/System/Linq/Single.cs:104
at (wrapper dynamic-method) System.Object.lambda_method(System.Runtime.CompilerServices.Closure,Microsoft.EntityFrameworkCore.Query.QueryContext)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult] (System.Linq.Expressions.Expression query) [0x00075] in <a3dbe48366454fdbb51dfeeb0b5c4997>:0
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult] (System.Linq.Expressions.Expression expression) [0x00000] in <a3dbe48366454fdbb51dfeeb0b5c4997>:0
at System.Linq.Queryable.FirstOrDefault[TSource] (System.Linq.IQueryable`1[T] source) [0x0000e] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-10/external/bockbuild/builds/mono-x64/external/corefx/src/System.Linq.Queryable/src/System/Linq/Queryable.cs:729
at GenericEFIAPI.RTATenantsDatabaseHelper.convertTenant (System.String tenantId, GenericEFIAPI.configObject config, GenericEFIAPI.models.TenantDatabase db) [0x002d2] in /Users/jft/projects/GenericAPI/GenericEFIAPI/RTATenantsDatabaseHelper.cs:108
at GenericEFIAPI.Program+<>c__DisplayClass1_0.<Main>b__0 (GenericEFIAPI.Program+Options o) [0x000c1] in /Users/jft/projects/GenericAPI/GenericEFIAPI/Program.cs:78
at CommandLine.ParserResultExtensions.WithParsed[T] (CommandLine.ParserResult`1[T] result, System.Action`1[T] action) [0x00011] in <68c69d6559fd42bc897efd2a474dfda9>:0
at GenericEFIAPI.Program.Main (System.String[] args) [0x00013] in /Users/jft/projects/GenericAPI/GenericEFIAPI/Program.cs:38
I've tried looking around on google for some help, but have come up empty so far... Anybody have any ideas? I'm trying to connect to sql server and using DbContextOptionsBuilder().UseSqlServer() for the underlying connection.
I'm currently getting my old windows laptop up and running to see if it is because I'm on a Mac or not, but I thought I would get this question out there in the mean time.
Alright! So I'm not 100% sure why my connection string is failing when passing it directly to the DbContextOptionsBuilder().UseSqlServer(connectionString), but if I create a SqlConnection object before that, and pass that as the parameter to UseSqlServer, it works.
So got a workaround, but not sure why the error happens when just passing the connection string.

SimpleInjector and Microsoft Webhook ASP.Net Webhooks

We had been successfully using the Microsoft ASP.Net Webhooks (specifically the Stripe one) in our WebAPI 2 project with Ninject. Recently we migrated to SimpleInjector and while everything else went well, we cannot get this webhook processor to work. It keeps throwing the following exception: System.MissingMethodException: 'No parameterless constructor defined for this object.'
The relevant stack traces are:
mscorlib.dll!System.RuntimeType.CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref System.Threading.StackCrawlMark stackMark) Unknown
mscorlib.dll!System.Activator.CreateInstance(System.Type type, bool nonPublic) Unknown
mscorlib.dll!System.Activator.CreateInstance(System.Type type) Unknown
Microsoft.AspNet.WebHooks.Common.dll!Microsoft.AspNet.WebHooks.Utilities.TypeUtilities.GetInstances<Microsoft.AspNet.WebHooks.IWebHookHandler>(System.Collections.Generic.IEnumerable<System.Reflection.Assembly> assemblies, System.Func<System.Type, bool> predicate) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.ReceiverServices.GetHandlers() Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.DependencyScopeExtensions.GetHandlers(System.Web.Http.Dependencies.IDependencyScope services = {SimpleInjector.Integration.WebApi.SimpleInjectorWebApiDependencyResolver}) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.WebHookReceiver.ExecuteWebHookAsync(string id = "", System.Web.Http.Controllers.HttpRequestContext context = {System.Web.Http.WebHost.WebHostHttpRequestContext}, System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Collections.Generic.IEnumerable<string> actions = {string[1]}, object data = {Newtonsoft.Json.Linq.JObject}) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<Microsoft.AspNet.WebHooks.WebHookReceiver.<ExecuteWebHookAsync>d__22>(ref Microsoft.AspNet.WebHooks.WebHookReceiver.<ExecuteWebHookAsync>d__22 stateMachine) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.WebHookReceiver.ExecuteWebHookAsync(string id, System.Web.Http.Controllers.HttpRequestContext context, System.Net.Http.HttpRequestMessage request, System.Collections.Generic.IEnumerable<string> actions, object data) Unknown
Microsoft.AspNet.WebHooks.Receivers.Stripe.dll!Microsoft.AspNet.WebHooks.StripeWebHookReceiver.ReceiveAsync(string id = "", System.Web.Http.Controllers.HttpRequestContext context = {System.Web.Http.WebHost.WebHostHttpRequestContext}, System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<Microsoft.AspNet.WebHooks.StripeWebHookReceiver.<ReceiveAsync>d__15>(ref Microsoft.AspNet.WebHooks.StripeWebHookReceiver.<ReceiveAsync>d__15 stateMachine) Unknown
Microsoft.AspNet.WebHooks.Receivers.Stripe.dll!Microsoft.AspNet.WebHooks.StripeWebHookReceiver.ReceiveAsync(string id, System.Web.Http.Controllers.HttpRequestContext context, System.Net.Http.HttpRequestMessage request) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.ProcessWebHook(string webHookReceiver = "stripe", string id = "") Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.<ProcessWebHook>d__3>(ref Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.<ProcessWebHook>d__3 stateMachine) Unknown
Microsoft.AspNet.WebHooks.Receivers.dll!Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.ProcessWebHook(string webHookReceiver, string id) Unknown
[Lightweight Function]
System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.GetExecutor.AnonymousMethod__8(object instance, object[] methodParameters) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Collections.Generic.IDictionary<string, object> arguments, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(System.Web.Http.Controllers.HttpActionContext actionContext = {System.Web.Http.Controllers.HttpActionContext}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0>(ref System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsyncCore(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ApiControllerActionInvoker.InvokeActionAsync(System.Web.Http.Controllers.HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2>(ref System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Controllers.ActionFilterResult.ExecuteAsync(System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.ApiController.ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1>(ref System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.Cors.dll!System.Web.Http.Cors.CorsMessageHandler.SendAsync(System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0>(ref System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0 stateMachine) Unknown
System.Web.Http.Cors.dll!System.Web.Http.Cors.CorsMessageHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request = {System.Net.Http.HttpRequestMessage}, System.Threading.CancellationToken cancellationToken = IsCancellationRequested = false) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.HttpServer.<SendAsync>d__0>(ref System.Web.Http.HttpServer.<SendAsync>d__0 stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(System.Web.HttpContextBase contextBase = {System.Web.HttpContextWrapper}) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.Web.Http.WebHost.HttpControllerHandler.<ProcessRequestAsyncCore>d__0>(ref System.Web.Http.WebHost.HttpControllerHandler.<ProcessRequestAsyncCore>d__0 stateMachine) Unknown
System.Web.Http.WebHost.dll!System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore(System.Web.HttpContextBase contextBase) Unknown
System.Web.dll!System.Web.TaskAsyncHelper.BeginTask(System.Func<System.Threading.Tasks.Task> taskFunc, System.AsyncCallback callback, object state = null) Unknown
System.Web.dll!System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() Unknown
System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step = {System.Web.HttpApplication.CallHandlerExecutionStep}, ref bool completedSynchronously = false) Unknown
System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error) Unknown
System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb) Unknown
System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr = {System.Web.Hosting.IIS7WorkerRequest}, System.Web.HttpContext context = {System.Web.HttpContext}) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext = 0x000002226c0521f0, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[AppDomain Transition]
And
System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Microsoft.AspNet.WebHooks.Utilities.TypeUtilities.GetInstances[T](IEnumerable`1 assemblies, Func`2 predicate)
at Microsoft.AspNet.WebHooks.ReceiverServices.GetHandlers()
at Microsoft.AspNet.WebHooks.DependencyScopeExtensions.GetHandlers(IDependencyScope services)
at Microsoft.AspNet.WebHooks.WebHookReceiver.<ExecuteWebHookAsync>d__22.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 Microsoft.AspNet.WebHooks.StripeWebHookReceiver.<ReceiveAsync>d__15.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 Microsoft.AspNet.WebHooks.Controllers.WebHookReceiversController.<ProcessWebHook>d__3.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.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.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.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.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.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.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.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
Our global.asax looks like this:
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Options.PropertySelectionBehavior = new
InjectPropertySelectionBehavior();
// Register our stuff
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver = new
SimpleInjectorWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
we're registering the WebHook handler like this:
container.Register<IWebHookHandler, StripeWebhookHandler>(Lifestyle.Singleton);
Has anyone gotten this to work with SimpleInjector? Or have any ideas what might be wrong?
Solution:
IWebhookHandler needs registered as a collection, so doing this:
container.Collection.Append(typeof(IWebHookHandler), typeof(StripeWebhookHandler));
instead of:
container.Register<IWebHookHandler, StripeWebhookHandler>(Lifestyle.Singleton);
was the trick!
I figured this out by stepping into the source of both the Microsoft Webhook assembly and SimpleInjector and found that when the Webhook assembly asked for all instances of type IWebhookHandler, SimpleInjector, in its GetServices implementation was trying to find all IEnumerable<IWebhookHandler> instead and so was coming up with nothing.
These kind of exceptions are thrown when trying to resolve a dependency that has parameter constructors but one or more of the parameters has not been registered and thus cannot be resolved, resulting in a fall back to a parameter-less constructor which in certain cases are absent.
Verify that you have registered all the components needed by WebHooks to work.

Categories