首页 > 解决方案 > Xamarin 发布模式失败,但调试模式工作(已在 AndroidManifest.xml 中添加了 INTERNET_PERMISSION)

问题描述

我的 Xamarin 跨平台应用程序在调试模式 (Android) 下运行良好,但是当我更改为发布时,它会引发异常。我已经搜索过以纠正这种情况。大多数帖子显示android.permission.INTERNET需要在 AndroidManifest.xml 文件中添加。但这对我的问题不起作用。

另外,无论 Linker 是 Sdk Assembly only 还是发布模式下的 None,它仍然不起作用。(我的应用基于 Android Pie 9.0 构建)

和例外:

Unhandled Exception:
04-21 22:37:08.972 E/mono    ( 5319): System.NullReferenceException: Object reference not set to an instance of an object.
04-21 22:37:08.972 E/mono    ( 5319):   at .Views.LoginPage+<SigninProcedure>d__2.MoveNext () [0x001d6] in LoginPage.xaml.cs:56 
04-21 22:37:08.972 E/mono    ( 5319): --- End of stack trace from previous location where exception was thrown ---
04-21 22:37:08.972 E/mono    ( 5319):   at (wrapper dynamic-method) System.Object.31(intptr,intptr)
04-21 22:37:08.972 E/mono    ( 5319):   at (wrapper native-to-managed) System.Object.31(intptr,intptr)
04-21 22:37:08.973 E/mono-rt ( 5319): [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object.
04-21 22:37:08.973 E/mono-rt ( 5319):   at Views.LoginPage+<SigninProcedure>d__2.MoveNext () [0x001d6] in LoginPage.xaml.cs:56 

<uses-permission android:name="android.permission.INTERNET" />

以下是我抛出异常时的代码:

public async Task<List<User>> FindExistUserAsync(string weburl, string username)
{
    string url = weburl + username;
    try
    {
        var response = await client.GetAsync(url);// throw exception after run this line.
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var JsonResult = response.Content.ReadAsStringAsync().Result;
            try
            {
                //Debug.WriteLine(JsonResult);
                var contentResp = JsonConvert.DeserializeObject<List<User>>(JsonResult);
                return contentResp;
            }
            catch (Exception ex) { Debug.WriteLine(ex.Message); return null; }
        }
    }
    catch (Exception ex) { Debug.WriteLine(ex.Message); return null; }
    return null;
}

标签: c#xamarinxamarin.formsxamarin.android

解决方案


我解决了这些问题。我在这里找到它:Android 8: Cleartext HTTP traffic not allowed。从 Android 9.0(API 级别 28)开始,默认情况下禁用明文支持。因此,当我尝试连接 Web 服务时,它会抛出异常。


推荐阅读