我写了下面的WinUI 3代码。这段代码的目的是使用CoreWebView2.CookieManager.AddOrUpdateCookie(Cookie)
设置一个cookie,但在初始化webview2时没有设置cookie。(我在WebView2中使用DevTools确认了这一点。)而且,应用程序从未崩溃。有什么解决办法吗?
MainWindow.xaml
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="WebView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WebView"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.UI.Xaml.Controls"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<controls:WebView2 x:Name="MyWebView" Grid.Row="1" Grid.ColumnSpan="2"
Source="https://www.microsoft.com" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Grid>
</Window>
MainWindow.xaml.cs
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
namespace WebView
{
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
MyWebView.CoreWebView2Initialized += WebviewLoaded;
}
public async void WebviewLoaded(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
await MyWebView.EnsureCoreWebView2Async();
var Cookie = MyWebView.CoreWebView2.CookieManager.CreateCookie("testcookie", "value", "https://test.com", "/");
Cookie.IsHttpOnly = true;
Cookie.IsSecure = true;
Cookie.Expires = (DateTime.Now.AddDays(10).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
Cookie.SameSite = CoreWebView2CookieSameSiteKind.None;
MyWebView.CoreWebView2.CookieManager.AddOrUpdateCookie(Cookie);
}
}
}
我刷新了我的操作系统,再次运行这个应用程序,但结果是一样的。
1条答案
按热度按时间xienkqul1#
我找到解决办法了。在调用
CoreWebView2.CookieManager.AddOrUpdateCookie(Cookie)
之前,WebView必须能够访问Cookie的站点。在本例中,webview的默认url是microsoft.com,因此我更改了cookie的域之前
var Cookie = MyWebView.CoreWebView2.CookieManager.CreateCookie("testcookie", "value", "https://test.com", "/");
之后
var Cookie = MyWebView.CoreWebView2.CookieManager.CreateCookie("testcookie", "value", ".microsoft.com", "/");