Winui 3 中的 WebView2:从本地文件系统加载 Ionic/Angular 应用程序时出现 CORS 错误

WebView2 in Winui 3: CORS errors when loading an Ionic/Angular application from the local file system

继我的 之后,我正在寻找一种方法来用某种 Windows 应用程序包装我的 Ionic/Angular 应用程序。我正在查看 Electron(并遇到问题),但也在调查我是否刚刚创建了自己的 WinUI3 应用程序并使用了 Webview2。

这里的相关代码是

await MyWebView.EnsureCoreWebView2Async();
MyWebView.CoreWebView2.Navigate("file:///D:/0/www/index.html"); // test while waiting how to load from Assets
//MyWebView.CoreWebView2.Navigate("ms-appx-web:///www/index.html");
MyWebView.CoreWebView2.OpenDevToolsWindow();

当我 运行 它在开发工具中尝试加载 js 文件时出现以下 CORS 错误 index.html

        Access to script at 'file:///D:/0/www/runtime.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    runtime.js:1 
                    
                 Failed to load resource: net::ERR_FAILED
    index.html:1 
                    
                 Access to script at 'file:///D:/0/www/polyfills.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    polyfills.js:1 
                    
                 Failed to load resource: net::ERR_FAILED
    index.html:1 
                    
                 Access to script at 'file:///D:/0/www/vendor.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    vendor.js:1 
                    
                 Failed to load resource: net::ERR_FAILED
    index.html:1 
                    
                 Access to script at 'file:///D:/0/www/main.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.
    main.js:1 
                    
                 Failed to load resource: net::ERR_FAILED

有什么办法可以解决这个问题吗?

看起来 的解决方案也解决了这个问题。

需要使用SetVirtualHostNameToFolderMapping

 await MyWebView.EnsureCoreWebView2Async();

 MyWebView.CoreWebView2.SetVirtualHostNameToFolderMapping(
     "appassets", "assets", CoreWebView2HostResourceAccessKind.Allow);
    
 MyWebView.Source = new Uri("http://appassets/www/index.html");
 MyWebView.CoreWebView2.OpenDevToolsWindow();

这现在找到了 index.html 并且加载它时没有 CORS 问题。