How do I access cookies in a Xamarin WebView?

笑着哭i 提交于 2019-12-06 06:34:30

You need to create a custom control in your PCL-Project and then add a custom webview for each platform. The platform secific implementation then gets the coockies and you can use it from your pcl-webview.

On Android you can get the cookies with following code:

var cookieHeader = CookieManager.Instance.GetCookie(url);

And on iOS:

NSHttpCookieStorage storage = NSHttpCookieStorage.SharedStorage;

Sourcecode on github: https://github.com/seansparkman/CookiesWebView

The great thing about Cookies in each of the mobile platforms is they are shared cookie containers across the app. The WebView doesn't hold the Cookie's the platform does and hence even HTTP calls and different WebView's can all access the same shared cookie container.

However they can be tricky to pull out of some platforms, in that reflection is needed. If your SSO solution only requires them going to webpages to sign on first, then they all share the same cookies anyway and you won't need to do any of this.

Android

Android has 2 separate cookie containers for HTTP and WebView's. Its the odd one out. Hence you have

    using System.Net.Http;

    private static CookieContainer _cookieContainer = new System.Net.CookieContainer();
    private static Android.Webkit.CookieManager _cookieManager = Android.Webkit.CookieManager.Instance;

With HTTP requests you do this

HttpClient client = new HttpClient(new HttpClientHandler() { CookieContainer = cookieContainer });

The WebView uses the other one and you can get and set cookies in each container.

iOS

This one is easy, they are all stored in

 NSHttpCookieStorage.SharedStorage.Cookies

WinRT

using Windows.Web.Http;  //NOT: Microsoft.Net.Http

var filter = new HttpBaseProtocolFilter();
HttpClient client = new HttpClient(filter);

// Use this, while it comes from an instance, its shared across everything.
filter.CookieManager
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!