I have the following plan in my Xamarin Project:
The existing API (not public) delivers a System.Net.CookieCollection.
How can I realise my idea, using a POST-Request with those cookies? Here's my base:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class WebPage : ContentPage
{
public WebPage(string url, CookieCollection cookies)
{
InitializeComponent();
BindingContext = new MainPageViewModel();
MyWebView.Source = "https://" + url;
}
}
Kind regards, localhorst27
You will have to create a custom renderer for the WebView
on both Android and iOS. That way you'll be able to inject the cookies into the Android WebView
and iOS UIWebView
. If you are not familiar with them, start here: Introduction to Custom Renderers
When you're familiar with how renderers work, follow this post by Christine Blanda on Xamarin forums: Setting Cookies in a WebView
I'll also post the code here to make sure it's preserved in case the original post goes down.
Android OnElementChanged
var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.RemoveAllCookie();
var cookies = UserInfo.CookieContainer.GetCookies(new System.Uri(AppInfo.URL_BASE));
for (var i = 0; i < cookies.Count; i++)
{
string cookieValue = cookies[i].Value;
string cookieDomain = cookies[i].Domain;
string cookieName = cookies[i].Name;
cookieManager.SetCookie(cookieDomain, cookieName + "=" + cookieValue);
}
iOS OnElementChanged
// Set cookies here
var cookieUrl = new Uri(AppInfo.URL_BASE);
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
foreach (var aCookie in cookieJar.Cookies)
{
cookieJar.DeleteCookie(aCookie);
}
var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);
IList<NSHttpCookie> eCookies =
(from object jCookie in jCookies
where jCookie != null
select (Cookie) jCookie
into netCookie select new NSHttpCookie(netCookie)).ToList();
cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With