需求:C#客户端程序, 窗口里嵌入一个web网页,可通过URL跳转的那种。并且,需要将登录的身份验证信息(token)设置到请求头里。
核心代码如下:
// 打开按钮的点击事件
private void openBtn_Click(object sender, EventArgs e)
{
string urlText = this.urlTextBox.Text;
Uri uri = new Uri(urlText);
this.webView.Source = uri;
}
// webview2 控件的 CoreWebView2InitializationCompleted 事件
private void webView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
webView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
webView.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = false;
//webView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
webView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
}
// 设置请求头信息
private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
{
e.Request.Headers.SetHeader("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyMDA2MTcyMDQyNDMxMzE0MTM4IiwiaWF0IjoxNzE4MjYxODczLCJleHAiOjE3MTgzMjE4NzN9.AUmUMQX2R-GgkQg_IvKphfgVagl-z96DwhdAh7z-9TZ5-y4cP_9YrsGlTGHF21nvm95BMjFdbpDDdST6w_3ivA");
}
实现的效果: