Webview2 在 WPF .Net Core 应用程序中无法工作。

3
我们已经安装了 Microsoft Edge WebView2 运行时(x86) 以供 WebView2 使用。请参考下面的截图。

enter image description here

我们正在使用.NET Core 3.1框架和WPF进行应用程序开发。 我们的webview2在Visual Studio的调试/发布/发布模式下运行良好,但是一旦安装我们的应用程序,它就无法加载。
当我们以普通权限运行应用程序时,它不会报任何错误,也不会被加载。 当我们以“管理员身份运行”它时,它会给出以下错误:

enter image description here

我们正在使用Visual Studio中的Windows Installer Project扩展来创建.MSI。
我们的XAML代码如下:
<UserControl x:Class="SampleApp.Views.SampleWebView"
             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:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
             xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="0.7*"/>
            <ColumnDefinition Width="0.3*"/>
            <ColumnDefinition Width="10"/>
        </Grid.ColumnDefinitions>
        <Border Grid.Column="1"  Margin="5" CornerRadius="10"  BorderThickness="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <Border.BitmapEffect>
                <DropShadowBitmapEffect Color="Black" Direction="40" ShadowDepth="2" Softness="1" Opacity="0.3" />
            </Border.BitmapEffect>
            <wv2:WebView2 x:Name="MyWebView" Source="{Binding UrlToGo}" Margin="5 2"/>
        </Border>
</Grid>

UrlToGo是来自我们的ViewModel的。请帮助我们解决。
1个回答

2
错误提示已经说明了问题,它没有在想要创建 UserDataFolder(其中包含缓存和cookie等)的'C:\Program files'文件夹中写入权限。
解决方案是在创建 WebView2 时指定 UserDataFolder。您可以像这样实现:
```csharp var env = await CoreWebView2Environment.CreateAsync(null, userDataFolder); var webView = new WebView2(env); ```
using Microsoft.Web.WebView2.Core;

string userDataFolder = Path.Combine(Path.GetTempPath(), "WhatEver");
webView21.CreationProperties = new CoreWebView2CreationProperties()
{
    UserDataFolder = userDataFolder
};
await webView21.EnsureCoreWebView2Async();

在调用EnsureCoreWebView2Async之前,不要设置Source属性。

当然,将“webView2”替换为您的WebView2控件名称。


1
是的,Poul Bak的答案是正确的 - 您需要明确指定用户数据文件夹。问题在于,用户数据文件夹的当前默认值与主机应用程序可执行文件的文件夹相同。通常,在开发代码时,主机应用程序具有写入调试文件夹的权限。通常,在通过安装程序部署到Program Files或类似位置时,主机应用程序将无法获得权限。即将推出的更改默认用户数据文件夹可能会有所帮助 https://github.com/MicrosoftEdge/WebView2Announcements/issues/26 - David Risney
@poul Bak感谢您的回复。它起作用了。我们正在使用PRISM框架的MVVM方法。您能告诉我可以在哪个事件名称中保留此代码,以便在绑定之前执行它吗?这可能听起来很傻,但由于我是WPF和MVVM的新手,因此需要您的帮助。 - Amol Pawar
这是你需要的吗?protected override async void OnContentRendered(EventArgs e) - Poul Bak
我们在用户控件中调用Webview2,当用户导航到该功能时,它会被加载。我们在用户控件中没有这个重写方法。在代码后台类中需要继承什么吗?或者是否有其他与此相当的用户控件方法? - Amol Pawar
只需在您的用户控件中定义一个公共方法,并在创建后调用它即可。 - Poul Bak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接