应用程序关闭时清除 Xamarin 表单 WebView cookie

Xamarin forms WebView cookies cleared when app closed

我有 android 的 Xamarin Forms WebView 应用程序。我能够在首次登录时完美地使用该应用程序。但是,如果我重新打开应用程序,WebView cookies 会清除,用户需要再次登录。 我希望用户在登录一次后不需要登录,即使他们关闭了应用程序。 这是我的代码:

 var wbURL = "https://www.example.com/login/";
 webrowser.Source = wbURL;

在 Android 上,cookie 应该自动存储,除非您使用自定义渲染器手动删除它们。

对于 iOS,您可以保存 cookie 并稍后恢复它们,如下所示:

保存cookies(用户登录后调用此方法,此代码放入WebView自定义渲染器):

public async Task SaveCookies()
{
    // For iOS < 10, cookies are saved in NSHTTPCookieStorage.sharedHTTPCookieStorage(), coojies should work withouth this
    if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
    {
        return;
    }

    try
    {
        var cookies = await Configuration.WebsiteDataStore.HttpCookieStore.GetAllCookiesAsync();
        var cachedCookies = cookies.Select(c => new Cookie(c.Name, c.Value, c.Path, c.Domain)
            {
                Secure = c.IsSecure,
                Version = Convert.ToInt32(c.Version)
            }).ToList();

            //TODO: Save the cachedCookies into app cache. You can create a service in the shared project
    }
    catch (Exception e)
    {
           
    }
}

恢复 cookie(在 WebView 自定义渲染器 OnElementChanged 方法中调用):

var store = WKWebsiteDataStore.NonPersistentDataStore;
await RestoreCookies(store);

private async Task RestoreCookies(WKWebsiteDataStore store)
{
    // For iOS < 10, cookies are saved in NSHTTPCookieStorage.sharedHTTPCookieStorage(), coojies should work withouth this
    if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
    {
        return;
    }

    if (store == null)
    {
        return;
    }

    await ClearCookies(store);
    var storedCookies = //TODO: Retreive cookies from where you sotred them

    foreach (Cookie cookie in storedCookies)
    {
        await store.HttpCookieStore.SetCookieAsync(new NSHttpCookie(cookie));
    }
}

private async Task ClearCookies(WKWebsiteDataStore store)
{
    var cookies = await store.HttpCookieStore.GetAllCookiesAsync();
    if (cookies?.Any() ?? false)
    {
        foreach (NSHttpCookie cookie in cookies)
        {
            await store.HttpCookieStore.DeleteCookieAsync(cookie);
        }
    }
}

编辑: 如果您在 Android 上也有问题,请在您的 WebView 自定义渲染器中尝试此代码:

 var cookieManager = CookieManager.Instance;
 cookieManager.SetAcceptCookie(true);
 cookieManager.AcceptCookie();
 cookieManager.Flush(); // Forces cookie sync