我正在开发一个使用 .Net5/WPF 显示 WebView2 的应用程序。
我想禁用 CORS。
我已经安装了 Chromium Edge Canary 86.0.607.0。
在 Edge 中,可以通过将以下参数添加到快捷方式来禁用 CORS。
--disable-web-security --user-data-dir="C://Chrome dev session"
我也想禁用 WebView2。
对于 WPF,在构造函数中调用以下代码
async void InitializeAsync()
{
var op = new CoreWebView2EnvironmentOptions("--disable-web-security");
var env = await CoreWebView2Environment.CreateAsync(null, null, op);
await webView.EnsureCoreWebView2Async(env);
}
我在这个论坛上得到了答案。对不起,这个网站是日文的。
https://social.msdn.microsoft.com/Forums/ja-JP/9bac6d51-94eb-42c8-96f0-4081e9a4056d/wpf-webview2-cors-?forum=wpfja
它与下面的代码一起工作。
*需要在WebView2.Source 中指定URL 之前进行设置。
注意不要在 Xaml 端指定 Source。
/// <summary>
/// WPF Window Constructor
/// </summary>
/// <param name="url">URL</param>
public WebViewWindow(string url)
{
InitializeComponent();
// async start
Loaded += async (_, __) => await _Routine(url);
}
/// <summary>
/// task
/// </summary>
/// <param name="url">URL</param>
/// <returns>task</returns>
async Task _Routine(string url)
{
var localPath = Environment.GetEnvironmentVariable("LocalAppData");
var webviewPath = $@"{localPath}\Microsoft\Edge SxS\Application\86.0.608.0";
var userPath = "C://Chrome dev session";
// Argument setting to disable COAR
var op = new CoreWebView2EnvironmentOptions("--disable-web-security");
var env = await CoreWebView2Environment.CreateAsync(webviewPath, userPath, op);
await webView.EnsureCoreWebView2Async(env);
if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri? result))
{
webView.Source = result;
}
}
另一种选择是创建一个虚拟主机。有关详细信息,请参阅CoreWebView2.SetVirtualHostNameToFolderMapping
:
设置虚拟主机名和文件夹路径之间的映射,以通过该主机名提供给网站。
例子:
public class VirtualHost
{
private WebView2 webView;
private string hostName;
private string directory;
public VirtualHost(WebView2 webView, string hostName, string directory)
{
this.webView = webView;
this.hostName = hostName;
this.directory = directory;
_ = InitializeAsync();
}
async private Task InitializeAsync()
{
// Wait for CoreWebView2 initialization.
// Explicitly triggers initialization of the control's CoreWebView2.
await webView.EnsureCoreWebView2Async();
// Set a mapping between a virtual host name and a folder path
// to make available to web sites via that host name.
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
hostName, directory, CoreWebView2HostResourceAccessKind.DenyCors);
webView.Source = new Uri($"https://{hostName}/index.html");
}
}
var localPath = Environment.GetEnvironmentVariable("LocalAppData");
virtualHost = new VirtualHost(view.configuratorWebView, "mylocalhost", localPath);