我已经在本地发布了一个C# WPF MVVM(Caliburn Micro)应用程序,并尝试使用WebView2显示网页时出现以下事件查看器消息。在调试中,网页可以正常显示。
说明:由于未处理的异常,进程被终止。 异常信息:System.DllNotFoundException:找不到DLL。 Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateCoreWebView2EnvironmentWithOptions(String browserExecutableFolder,String userDataFolder,ICoreWebView2EnvironmentOptions options,ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler environment_created_handler) Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(String browserExecutableFolder,String userDataFolder,CoreWebView2EnvironmentOptions options) IGPC2WPF.Views.BrowserView.InitializeAsync()
我发现它与userDataFolder相关,已经尝试了一些来自Stack Overflow的解决方案,但仍然没有成功。
我不明白的是,似乎创建了一个EBWebView文件夹,我认为它是userData文件夹,那么为什么会出现错误?是否存在某些权限问题?
WebView2Loader.dll位于发布目录中。
EBWebView的位置是:C:\Users*****\AppData\Local\Temp\IGPC2WPF\EBWebView
这是显示网站的文件的XAML和代码。
XAML视图
<UserControl x:Class="IGPC2WPF.Views.BrowserView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:IGPC2WPF.Views"
xmlns:cal="http://caliburnmicro.com"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
mc:Ignorable="d" Background="#3b3b3b"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<wv2:WebView2 x:Name="WebView" Source="{Binding PdfAddress, Mode=TwoWay}" />
</Grid>
视图模型
private string _address;
private readonly IEventAggregator _events;
private readonly IConfiguration _config;
public string Address
{
get { return _address; }
set { _address = value; NotifyOfPropertyChange(() => Address); }
}
public BrowserViewModel(IEventAggregator events, IConfiguration config)
{
_events = events;
_config = config;
_address = _config.GetValue<string>("MiscURLs:WorkToListReport");
}
public void Close()
{
_events.PublishOnUIThreadAsync(new GenerateExcelDataEvent());
TryCloseAsync();
}
后台代码:
public partial class BrowserView : UserControl
{
public WebPageView()
{
InitializeComponent();
InitializeAsync();
}
async void InitializeAsync()
{
string userDataFolder = Path.Combine(Path.GetTempPath(), "IGPC2WPF");
WebView.CreationProperties = new()
{
UserDataFolder = userDataFolder
};
await WebView.EnsureCoreWebView2Async(null);
}
}
编辑 好的,看起来问题出在我在发布目录中运行setup.exe时,存在的WebView2Loader.dll没有被复制到安装目录中。如果我手动将它移动到安装位置,网页可以正常显示。
如何确保这个dll在ClickOnce中被复制过去呢?
WebView2Loader.dll
部署中,那么您可以尝试按照 https://learn.microsoft.com/en-us/microsoft-edge/webview2/how-to/static 中所述将其静态链接。 - SergSource
属性:Source="{Binding PdfAddress, Mode=TwoWay}"
。然后你就不能设置 userdatafolder,因为WebView2
环境已经被创建并且await WebView.EnsureCoreWebView2Async(null);
被忽略了。 - Poul Bak