首页 > 解决方案 > Xamarin 形成 WebView 丢失 Session/Cookie

问题描述

Webview在 Xamarin Forms 应用程序中使用。正如我们在下面的代码中看到的,我正在设置一个特定的 cookie。

问题: Webview正在正确打开并且页面已加载,但该网站包含一个“下一步”按钮,该按钮将引导我们进入另一个网页。每当我按下 Next 时,我都会直接得到一个Session Timeout。就像我在其中导航时,Webview 不会保存 cookie。

WebScreen.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         mc:Ignorable="d"
         x:Class="EPayment.Views.DetailViews.WebScreen">
<ContentPage.Content>
    <StackLayout>
        <WebView x:Name="paymentWebView" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
                 Navigated="paymentWebView_Navigated" Navigating="paymentWebView_Navigating"/>
    </StackLayout>
</ContentPage.Content>

WebScreen.xaml.cs:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class WebScreen : ContentPage
{
    public WebScreen(HtmlWebViewSource webSource)
    {
        InitializeComponent();
        paymentWebView.Source = webSource;
    }

    private void paymentWebView_Navigated(object sender, WebNavigatedEventArgs e) { }

    private void paymentWebView_Navigating(object sender, WebNavigatingEventArgs e) { }
}

这是我开始WebScreen上课的方式:

var httpDate = DateTime.Now.ToString("r");
var cookieValue = httpDate;
var encodedCookie = HttpUtility.UrlEncode(cookieValue);
cookieContainer.Add(baseAddress, new Cookie("cookie", encodedCookie));
var result = await client.PostAsync("/pay", content);
if (result.IsSuccessStatusCode)
{
    var resp = await result.Content.ReadAsStringAsync();
    var html = new HtmlWebViewSource
    {
        Html = resp,
        BaseUrl = "https://testsecureacceptance.cybersource.com"
    };
    await Navigation.PushAsync(new WebScreen(html));
}

任何人都知道这种问题的解决方案是什么?有没有办法保存 cookie 或选项或类似的东西?

标签: c#xamarin.formswebview

解决方案


推荐阅读