How do I access cookies in a Xamarin WebView?

浪尽此生 提交于 2019-12-10 11:09:27

问题


In our Xamarin app, we need to allow our users to log in using their own SSO solution.

The way this works in our iOS app is that we open up a controller with a web view and point it at our site, and keep watching the cookies until they're back on our site with the cookie that indicates that they're logged in. But in Xamarin, I can't see how I can access the cookies for the WebView. Our Xamarin app is running on Windows 8.1 and WinPhone 8.1, but it will be extended to Android at some point so I need a cross-platform solution.

So, how do I access cookies in a Xamarin WebView?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/38892037/how-do-i-access-cookies-in-a-xamarin-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!