C# webview2 获取cookie
时间: 2023-07-24 10:17:02 浏览: 618
你可以使用以下的代码来获取 WebView2 中的 Cookie:
```csharp
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
namespace WebView2Cookie
{
public class WebView2CookieHelper
{
public async Task<string> GetCookie(string url)
{
string cookie = string.Empty;
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await CoreWebView2Environment.CreateAsync();
var webView = new WebView2();
await webView.EnsureCoreWebView2Async();
webView.NavigationStarting += async (s, e) =>
{
var cookieManager = webView.CoreWebView2.CookieManager;
var uri = new Uri(url);
var cookies = await cookieManager.GetCookiesAsync(uri.ToString());
cookie = string.Join(";", cookies.Select(c => $"{c.Name}={c.Value}"));
};
await webView.CoreWebView2.Navigate(url);
});
return cookie;
}
}
}
```
使用时,只需要传入你需要获取 Cookie 的 URL,例如:
```csharp
var helper = new WebView2CookieHelper();
var cookie = await helper.GetCookie("https://www.example.com");
```
其中,`cookie` 即为获取到的 Cookie。
阅读全文