Webview2 在 WPF .Net 核心应用程序设置中不起作用

Webview2 is not working in WPF .Net Core App setup

我们已经为 WebView2 安装了 Microsoft Edge WebView2 运行time(x86)。参考以下 SS.

我们正在使用 .NET Core 3.1 框架和 WPF 进行应用程序开发。 我们的 webview2 运行 在 Visual Studio 中的 debug/release/publish 模式下很好,但是一旦我们安装了我们的应用程序就不会加载它。

当我们 运行 具有正常权限且未加载的应用程序时,也不会出现任何错误。 当我们 运行 它作为“运行 作为管理员”时,它给出以下错误,

我们在 Visual studio 中使用 Windows 安装程序项目扩展来创建 .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。

请大家帮忙解决。

错误说明了一切,它没有对要创建 UserDataFolder(包含缓存和 cookie 等)的 'C:\Program files' 的写入权限。

解决方法是在创建WebView2时指定UserDataFolder。你这样做:

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 控件的名称。