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

.NET 8 MAUI Android迁移后HttpClient调用API遇NullReferenceException求助

求助:调用HttpClient.PostAsync时触发NullReferenceException异常

异常信息

异常类型:System.NullReferenceException
错误消息:The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class.

触发场景

调用以下HttpClient代码请求API时出现该异常:

var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await _client.PostAsync(uri, content);

运行环境

  • .NET 8
  • Android
  • MAUI
  • Visual Studio

背景情况

将基于.NET Framework的Android Xamarin应用升级至MAUI

相关代码

MainActivity类代码

[Activity(Name = "Test.MainActivity", Label = "Test Mobile", Icon = "@drawable/icon"
    , LaunchMode = LaunchMode.SingleTask, MainLauncher = true, ScreenOrientation = ScreenOrientation.Portrait, Theme = "@style/Maui.SplashTheme"
    , ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Microsoft.Maui.MauiAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }

    // for FCM push notifications
    internal static readonly string CHANNEL_ID = "fcm_notification_channel";
    internal static readonly int NOTIFICATION_ID = 100;

    enum EnvCheckType { Root, Debug, Emulator, Hooks, CustomFirmware, IntegrityCheck, WirelessSecurity };
    static BitArray envChecks = new BitArray(7);

    private MyBroadcastReceiver mMessageReceiver = new MyBroadcastReceiver();

    protected override void OnCreate(Bundle savedInstanceState)
    {
        try
        {
            Instance = this;

            base.OnCreate(savedInstanceState);
        }
        catch (Exception ex)
        {
            ExceptionLogger.LogErrorAsync(ex);
        }
    }
}

MainApplication类代码

[Application]
public class MainApplication : MauiApplication
{
    // for FCM push notifications
    internal static readonly string CHANNEL_ID = "fcm_notification_channel";
    internal static readonly int NOTIFICATION_ID = 100;

    enum EnvCheckType { Root, Debug, Emulator, Hooks, CustomFirmware, IntegrityCheck, WirelessSecurity };
    static BitArray envChecks = new BitArray(7);

    public MainApplication(nint handle, JniHandleOwnership ownership) : base(handle, ownership)
    {
    }

    protected override MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder.UseMauiApp<App>().UseMauiCommunityToolkit();
        
        return builder.Build();
    }
}

已尝试操作

调整过MainActivity和HttpClient相关代码,但问题仍未解决,恳请各位提供解决建议。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:01:23