首页 > 解决方案 > 当密钥不存在时,SecureStorage 不会抛出异常

问题描述

我的应用程序中发生了一个奇怪的错误。

我有一个非常简单的辅助方法,用于在用户设备上存储一些很酷的数据:

public static async Task TrySetAsync(string key, string value)
    {
        try
        {
            await SecureStorage.SetAsync(key, value);
        }
        catch (Exception ex)
        {
            await App.Current.MainPage.DisplayAlert(
                "Device incompatible",
                "Your device is not compatible with this app.",
                "Ok");
        }
    }

它工作得很好,从来没有问题,但我决定在应用程序启动时执行兼容性检查,以便用户立即知道他们的设备不会切断它。为此,我决定在初始登录页面的OnAppearing()方法中实现它。它看起来像这样:

protected override async void OnAppearing()
    {
        try
        {
            // Try to save data to a random container
            string tempKey = System.Guid.NewGuid().ToString();

            //  Should throw an exception if SecureStorage is not compatible
            await Xamarin.Essentials.SecureStorage
                .SetAsync(tempKey, string.Empty);

            // Remove the datum
            Xamarin.Essentials.SecureStorage
                .Remove(tempKey);
        }
        catch
        {
            await App.Current.MainPage.DisplayAlert(
                "Device incompatible", 
                "This device does not support secure storage required for the application.", 
                "Ok");

            App.Terminate();
        }


        base.OnAppearing();
    }

我从项目中删除了权利来测试我的小混合物,但是,它毫无问题地通过了它。不会抛出异常。但是在登录时,使用原始 TrySetAsync 方法(第一个代码片段)时,会引发预期的异常(缺少权利)。调试器进入 try 块并让它没有问题。

总之:

看来,当在OnAppearing()中引用 SecureStorage 时,该应用程序不需要任何权利,但在主 App 类中定义的 TrySetAsync(...) 中引发了预期的异常。

有什么建议吗?

PS 最初我在 OnAppearing() 中使用 GetAsync 和一个随机的 guid 字符串,我将其更改为 SetAsync 和 Remove,认为可能获取数据不需要兼容性。一般来说,我从来没有遇到过这样的 SecureStorage 问题,而且对我来说这确实像是一些内部错误。\

回答

我不喜欢使用 string.Empty 作为值。看来 SecureStorage.SetAsync 将忽略此类值并且不存储它,这样就不会引发任何异常。此外,尝试从 SecureStorage 获取不存在的密钥也不会导致缺少授权异常

标签: xamarinxamarin.formsxamarin.iosxamarin.essentials

解决方案


(OP自己回答了这个问题):

我不喜欢使用 string.Empty 作为值。看来 SecureStorage.SetAsync 将忽略此类值并且不存储它,这样就不会引发任何异常。此外,尝试从 SecureStorage 获取不存在的密钥也不会导致缺少授权异常


推荐阅读