System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

你好,我正在用 C# 开发 VPN,这是我的代码

VpnManagementAgent vpnManagementAgent = new VpnManagementAgent();
        VpnManagementAgent mgr = vpnManagementAgent;
        VpnNativeProfile profile = new VpnNativeProfile()
        {
            AlwaysOn = false,
            NativeProtocolType = VpnNativeProtocolType.IpsecIkev2,
            ProfileName = "MyConnection",
            RememberCredentials = true,
            RequireVpnClientAppUI = true,
            RoutingPolicyType = VpnRoutingPolicyType.SplitRouting,
            TunnelAuthenticationMethod = VpnAuthenticationMethod.Certificate,
            UserAuthenticationMethod = VpnAuthenticationMethod.Mschapv2,
        };
        profile.Servers.Add("serveAddress");
        VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);
        PasswordCredential credentials = new PasswordCredential
        {
            UserName = "username",
            Password = "Abc",
        };
        VpnManagementErrorStatus connectStatus = await mgr.ConnectProfileWithPasswordCredentialAsync(profile, credentials);

我在按钮操作上添加了所有这些代码。现在当我开始 VPN 连接时,这条线抛出异常

VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);

例外是

 System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

堆栈跟踪:

at Windows.Networking.Vpn.VpnManagementAgent.AddProfileFromObjectAsync(IVpnProfile profile)
at App1.MainPage.<Button_Click>d__2.MoveNext() in C:\Users\HP\source\repos\StarkVPnTesting\App1\MainPage.xaml.cs:line 62

我认为您需要按照以下方式添加应用功能 "networkingVpnProvider":

此 link 描述了重要性以及如何应用 App Capabilities MSDN App Capability。最后,您需要将以下内容添加到您的应用程序包清单源文件 (Package.appxmanifest)。

<?xml version="1.0" encoding="utf-8"?>
<Package
    ...
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="... rescap">
...
<Capabilities>
    <rescap:Capability Name="networkingVpnProvider"/>
</Capabilities>
</Package>

请注意,根据该方法的文档,这是 Windows10 的要求:VpnManagementAgent.AddProfileFromObjectAsync(IVpnProfile) Method