You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui Android测试应用连接Azure SQL DB时出现异常

问题描述

我编写了一段简单代码用于测试连接Azure SQL DB,向“Utenti”表插入新数据,代码如下:

Microsoft.Data.SqlClient.SqlConnection sqlConnection1 =
new Microsoft.Data.SqlClient.SqlConnection("connection string");

Microsoft.Data.SqlClient.SqlCommand cmd = new Microsoft.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT utente (ID, password, nome_ut, image) VALUES (5, 'NorthWestern', 'ciao', 'aaa')";
cmd.Connection = sqlConnection1;

sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();

该代码在Windows机器上运行正常,能成功向数据库插入数据,但在Android端运行时抛出如下异常:

{System.TypeInitializationException: The type initializer for
'Microsoft.Data.SqlClient.SqlAuthenticationProviderManager' threw an
exception. ---> System.TypeInitializationException: The type
initializer for
'Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider' threw
an exception. ---> System.Configuration.ConfigurationErrorsException:
Configuration system failed to initialize --->
System.PlatformNotSupportedException: Operation is not supported on
this platform. 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.PrepareConfigSystem() at
System.Configuration.ConfigurationManager.GetSection(String
sectionName) at
System.Runtime.Caching.MemoryCacheStatistics.InitializeConfiguration(NameValueCollection
config) at
System.Runtime.Caching.MemoryCacheStatistics..ctor(MemoryCache
memoryCache, NameValueCollection config) at
System.Runtime.Caching.MemoryCache.InitDisposableMembers(NameValueCollection
config) at
System.Runtime.Caching.MemoryCache.Init(NameValueCollection config)

at System.Runtime.Caching.MemoryCache..ctor(String name,
NameValueCollection config) at
Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider..cctor()
in
D:\a_work\1\s\src\Microsoft.Data.SqlClient\src\Microsoft\Data\SqlClient\ActiveDirectoryAuthenticationProvider.cs:line
30 --- End of inner exception stack trace --- at
Microsoft.Data.SqlClient.SqlAuthenticationProviderManager.SetDefaultAuthProviders(SqlAuthenticationProviderManager
instance) in
D:\a_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlAuthenticationProviderManager.cs:line
42 at
Microsoft.Data.SqlClient.SqlAuthenticationProviderManager..cctor() in
D:\a_work\1\s\src\Microsoft.Data.SqlClient\netcore\src\Microsoft\Data\SqlClient\SqlAuthenticationProviderManager.NetCoreApp.cs:line
37 --- End of inner exception stack trace --- at
MilestoneGP_app.MainPage.OnCounterClicked(Object sender, EventArgs e)
in
C:\Users\pelli\source\repos\MilestoneGP_app\MilestoneGP_app\MainPage.xaml.cs:line
46 at
Microsoft.Maui.Controls.Button.Microsoft.Maui.Controls.Internals.IButtonElement.PropagateUpClicked()
in
D:\a_work\1\s\src\Controls\src\Core\Button\Button.cs:line 275 at
Microsoft.Maui.Controls.ButtonElement.ElementClicked(VisualElement
visualElement, IButtonElement ButtonElementManager) in
D:\a_work\1\s\src\Controls\src\Core\Button\ButtonElement.cs:line 40

at Microsoft.Maui.Controls.Button.SendClicked() in
D:\a_work\1\s\src\Controls\src\Core\Button\Button.cs:line 250 at
Microsoft.Maui.Controls.Button.Microsoft.Maui.IButton.Clicked() in
D:\a_work\1\s\src\Controls\src\Core\Button\Button.cs:line 484 at
Microsoft.Maui.Handlers.ButtonHandler.OnClick(IButton button, View v)
in
D:\a_work\1\s\src\Core\src\Handlers\Button\ButtonHandler.Android.cs:line
148 at
Microsoft.Maui.Handlers.ButtonHandler.ButtonClickListener.OnClick(View
v) in
D:\a_work\1\s\src\Core\src\Handlers\Button\ButtonHandler.Android.cs:line
169 at
Android.Views.View.IOnClickListenerInvoker.n_OnClick_Landroid_view_View_(IntPtr
jnienv, IntPtr native__this, IntPtr native_v) in
/Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/net8.0/android-34/mcw/Android.Views.View.cs:line
2374 at
Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPL_V(_JniMarshal_PPL_V
callback, IntPtr jnienv, IntPtr klazz, IntPtr p0) in
/Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:line
125}

我使用的是.NET Maui 8.0,首次尝试为Android应用连接数据库,恳请帮助解决该问题。

# 解决方案
## 问题根源
异常核心是`System.PlatformNotSupportedException`:Microsoft.Data.SqlClient在Android平台默认尝试初始化Active Directory认证组件,而该组件依赖的`System.Configuration.ConfigurationManager`在Android上不被支持,进而引发一系列类型初始化失败。

## 修复步骤
1. **修改连接字符串,指定SQL Server认证方式**
   在连接字符串中添加`Authentication=SqlPassword`,强制使用SQL账号密码认证,绕开AD认证逻辑。示例连接字符串:

"Server=tcp:你的服务器名.database.windows.net,1433;Initial Catalog=你的数据库名;Persist Security Info=False;User ID=你的账号;Password=你的密码;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Authentication=SqlPassword"

2. **更新Microsoft.Data.SqlClient版本**
确保使用v5.x及以上版本的NuGet包,新版本对.NET MAUI的跨平台支持更完善。

3. **优化代码资源管理**
使用`using`语句自动释放数据库连接资源,避免内存泄漏:
```csharp
using (var sqlConnection1 = new Microsoft.Data.SqlClient.SqlConnection("带Authentication=SqlPassword的连接字符串"))
{
    var cmd = new Microsoft.Data.SqlClient.SqlCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "INSERT utente (ID, password, nome_ut, image) VALUES (5, 'NorthWestern', 'ciao', 'aaa')";
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
}

最佳实践

不建议直接在MAUI客户端连接Azure SQL DB:

  • 连接字符串硬编码在客户端易被反编译泄露,存在安全风险
  • 推荐搭建ASP.NET Core Web API中间层,客户端通过调用API来操作数据库,既安全又符合移动应用架构规范

内容的提问来源于stack exchange,提问作者Pelliz18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:12:32