我正在开发一个使用.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}MicrosoftEdge SxSApplication86.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);