将cookie放在Xamarin的WebView上

时间:2017-03-17 09:26:02

标签: c# xamarin post cookies xamarin.forms

我的Xamarin项目中有以下计划:

  • 用户在MainPage上输入他的用户名和密码。
  • 如果数据正确(存在API),请导航到WebView和 在此页面上自动登录用户。

现有API(非公开)提供System.Net.CookieCollection。

如何使用带有这些Cookie的POST请求来实现我的想法?这是我的基础:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class WebPage : ContentPage
{
    public WebPage(string url, CookieCollection cookies)
    {
        InitializeComponent();
        BindingContext = new MainPageViewModel();
        MyWebView.Source = "https://" + url;

    }
}

亲切的问候, localhorst27

1 个答案:

答案 0 :(得分:5)

您必须在Android和iOS上为WebView创建自定义渲染器。这样,您就可以将Cookie注入Android WebView和iOS UIWebView。如果您不熟悉它们,请从这里开始:Introduction to Custom Renderers

如果您熟悉呈现器的工作方式,请在Xamarin论坛上Christine Blanda关注此帖:Setting Cookies in a WebView

我也会在此处发布代码,以确保在原始帖子发布时保留该代码。

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);