您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:使用 Kestrel 向 ASP.NET Core Web API 前端服务添加 HTTPS 终结点Tutorial: Add an HTTPS endpoint to an ASP.NET Core Web API front-end service using Kestrel

本教程是一个系列中的第三部分。This tutorial is part three of a series. 你将了解如何在 ASP.NET Core 服务(在 Service Fabric 上运行)中启用 HTTPS。You will learn how to enable HTTPS in an ASP.NET Core service running on Service Fabric. 完成后,你会有一个通过已启用 HTTPS 的 ASP.NET Core Web 前端在端口 443 上进行侦听的投票应用程序。When you're finished, you have a voting application with an HTTPS-enabled ASP.NET Core web front-end listening on port 443. 如果不希望根据生成 .NET Service Fabric 应用程序中的说明手动创建投票应用程序,可以下载源代码(适用于已完成的应用程序)。If you don't want to manually create the voting application in Build a .NET Service Fabric application, you can download the source code for the completed application.

在该系列的第三部分中,你会学习如何:In part three of the series, you learn how to:

  • 在服务中定义一个 HTTPS 终结点Define an HTTPS endpoint in the service
  • 将 Kestrel 配置为使用 HTTPSConfigure Kestrel to use HTTPS
  • 在远程群集节点上安装 SSL 证书Install the SSL certificate on the remote cluster nodes
  • 允许 NETWORK SERVICE 访问证书的私钥Give NETWORK SERVICE access to the certificate's private key
  • 在 Azure 负载均衡器中打开端口 443Open port 443 in the Azure load balancer
  • 将应用程序部署到远程群集Deploy the application to a remote cluster

在此系列教程中,你会学习如何:In this tutorial series you learn how to:

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

先决条件Prerequisites

在开始学习本教程之前:Before you begin this tutorial:

获取证书或创建自签名开发证书Obtain a certificate or create a self-signed development certificate

对于生产应用程序,请使用证书颁发机构 (CA) 提供的证书。For production applications, use a certificate from a certificate authority (CA). 出于开发和测试目的,可以创建并使用自签名证书。For development and test purposes, you can create and use a self-signed certificate. Service Fabric SDK 提供的 CertSetup.ps1 脚本可创建自签名证书并将其导入 Cert:\LocalMachine\My 证书存储。The Service Fabric SDK provides the CertSetup.ps1 script, which creates a self-signed certificate and imports it into the Cert:\LocalMachine\My certificate store. 以管理员身份打开命令提示符并运行以下命令即可创建使用者为“CN=mytestcert”的证书:Open a command prompt as administrator and run the following command to create a cert with the subject "CN=mytestcert":

PS C:\program files\microsoft sdks\service fabric\clustersetup\secure> .\CertSetup.ps1 -Install -CertSubjectName CN=mytestcert

如果已经有证书 PFX 文件,请运行以下命令,将证书导入 Cert:\LocalMachine\My 证书存储:If you already have a certificate PFX file, run the following to import the certificate into the Cert:\LocalMachine\My certificate store:


PS C:\mycertificates> Import-PfxCertificate -FilePath .\mysslcertificate.pfx -CertStoreLocation Cert:\LocalMachine\My -Password (ConvertTo-SecureString "!Passw0rd321" -AsPlainText -Force)


   PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\My

Thumbprint                                Subject
----------                                -------
3B138D84C077C292579BA35E4410634E164075CD  CN=zwin7fh14scd.westus.cloudapp.azure.com

在服务清单中定义一个 HTTPS 终结点Define an HTTPS endpoint in the service manifest

管理员身份启动 Visual Studio,然后打开 Voting 解决方案。Launch Visual Studio as an administrator and open the Voting solution. 在解决方案资源管理器中,打开 VotingWeb/PackageRoot/ServiceManifest.xmlIn Solution Explorer, open VotingWeb/PackageRoot/ServiceManifest.xml. 服务清单定义服务终结点。The service manifest defines the service endpoints. 找到 Endpoints 节,编辑现有的“ServiceEndpoint”终结点。Find the Endpoints section and edit the existing "ServiceEndpoint" endpoint. 将名称更改为“EndpointHttps”,将协议设置为 https,类型设置为 Input,端口设置为 443Change the name to "EndpointHttps", set the protocol to https, the type to Input, and port to 443. 保存所做更改。Save your changes.

<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="VotingWebPkg"
                 Version="1.0.0"
                 xmlns="http://schemas.microsoft.com/2011/01/fabric"
                 xmlns:xsd="https://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance">
  <ServiceTypes>
    <StatelessServiceType ServiceTypeName="VotingWebType" />
  </ServiceTypes>

  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <ExeHost>
        <Program>VotingWeb.exe</Program>
        <WorkingFolder>CodePackage</WorkingFolder>
      </ExeHost>
    </EntryPoint>
  </CodePackage>

  <ConfigPackage Name="Config" Version="1.0.0" />

  <Resources>
    <Endpoints>
      <Endpoint Protocol="https" Name="EndpointHttps" Type="Input" Port="443" />
    </Endpoints>
  </Resources>
</ServiceManifest>

将 Kestrel 配置为使用 HTTPSConfigure Kestrel to use HTTPS

在“解决方案资源管理器”中,打开 VotingWeb/VotingWeb.cs 文件。In Solution Explorer, open the VotingWeb/VotingWeb.cs file. 将 Kestrel 配置为使用 HTTPS,并在 Cert:\LocalMachine\My 存储中查找证书。Configure Kestrel to use HTTPS and lookup the certificate in the Cert:\LocalMachine\My store. 添加以下 using 语句:Add the following using statements:

using System.Net;
using Microsoft.Extensions.Configuration;
using System.Security.Cryptography.X509Certificates;

更新 ServiceInstanceListener,以便使用新的 EndpointHttps 终结点并在端口 443 上进行侦听。Update the ServiceInstanceListener to use the new EndpointHttps endpoint and listen on port 443. 配置使用 Kestrel 服务器的 Web 主机时,须将 Kestrel 配置为针对所有网络接口上的 IPv6 地址进行侦听:opt.Listen(IPAddress.IPv6Any, port, listenOptions => {...}When configuring the web host to use Kestrel server, you must configure Kestrel to listen for IPv6 addresses on all network interfaces: opt.Listen(IPAddress.IPv6Any, port, listenOptions => {...}.

new ServiceInstanceListener(
serviceContext =>
    new KestrelCommunicationListener(
        serviceContext,
        "EndpointHttps",
        (url, listener) =>
        {
            ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

            return new WebHostBuilder()
                .UseKestrel(opt =>
                {
                    int port = serviceContext.CodePackageActivationContext.GetEndpoint("EndpointHttps").Port;
                    opt.Listen(IPAddress.IPv6Any, port, listenOptions =>
                    {
                        listenOptions.UseHttps(GetHttpsCertificateFromStore());
                        listenOptions.NoDelay = true;
                    });
                })
                .ConfigureAppConfiguration((builderContext, config) =>
                {
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                })

                .ConfigureServices(
                    services => services
                        .AddSingleton<HttpClient>(new HttpClient())
                        .AddSingleton<FabricClient>(new FabricClient())
                        .AddSingleton<StatelessServiceContext>(serviceContext))
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                .UseUrls(url)
                .Build();
        }))

另请添加以下方法,这样 Kestrel 就能通过使用者在 Cert:\LocalMachine\My 存储中找到证书。Also add the following method so that Kestrel can find the certificate in the Cert:\LocalMachine\My store using the subject.

如果已使用以前的 PowerShell 命令创建自签名证书,请将“<your_CN_value>”替换为“mytestcert”,或者使用证书的 CN。Replace "<your_CN_value>" with "mytestcert" if you created a self-signed certificate with the previous PowerShell command, or use the CN of your certificate. 请注意,在本地部署到 localhost 的情况下,最好使用“CN=localhost”以避免身份验证异常。Be aware that in the case of local deployment to localhost it's preferable to use "CN=localhost" to avoid authentication exceptions.

private X509Certificate2 GetHttpsCertificateFromStore()
{
    using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
    {
        store.Open(OpenFlags.ReadOnly);
        var certCollection = store.Certificates;
        var currentCerts = certCollection.Find(X509FindType.FindBySubjectDistinguishedName, "CN=<your_CN_value>", false);
        
        if (currentCerts.Count == 0)
                {
                    throw new Exception("Https certificate is not found.");
                }
        
        return currentCerts[0];
    }
}

允许 NETWORK SERVICE 访问证书的私钥Give NETWORK SERVICE access to the certificate's private key

在前面的步骤中,已在开发计算机上将证书导入 Cert:\LocalMachine\My 存储。In a previous step, you imported the certificate into the Cert:\LocalMachine\My store on the development computer. 现在,显式允许运行服务(默认为 NETWORK SERVICE)的帐户访问证书的私钥。Now, explicitly give the account running the service (NETWORK SERVICE, by default) access to the certificate's private key. 可以手动执行此步骤(使用 certlm.msc 工具),但最好是在服务清单的 SetupEntryPoint配置启动脚本,以便自动运行 PowerShell 脚本。You can do this step manually (using the certlm.msc tool), but it's better to automatically run a PowerShell script by configuring a startup script in the SetupEntryPoint of the service manifest.

配置服务安装程序入口点Configure the service setup entry point

在解决方案资源管理器中,打开 VotingWeb/PackageRoot/ServiceManifest.xmlIn Solution Explorer, open VotingWeb/PackageRoot/ServiceManifest.xml. CodePackage 节中添加 SetupEntryPoint 节点,然后添加 ExeHost 节点。In the CodePackage section, add SetupEntryPoint node and then a ExeHost node. ExeHost 中将 Program 设置为“Setup.bat”,将 WorkingFolder 设置为“CodePackage”。In ExeHost, set Program to "Setup.bat" and WorkingFolder to "CodePackage". 当 VotingWeb 服务启动时,先是 Setup.bat 脚本在 CodePackage 文件夹中执行,然后 VotingWeb.exe 才会启动。When the VotingWeb service starts, the Setup.bat script executes in the CodePackage folder before VotingWeb.exe starts.

<?xml version="1.0" encoding="utf-8"?>
<ServiceManifest Name="VotingWebPkg"
                 Version="1.0.0"
                 xmlns="http://schemas.microsoft.com/2011/01/fabric"
                 xmlns:xsd="https://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance">
  <ServiceTypes>
    <StatelessServiceType ServiceTypeName="VotingWebType" />
  </ServiceTypes>

  <CodePackage Name="Code" Version="1.0.0">
    <SetupEntryPoint>
      <ExeHost>
        <Program>Setup.bat</Program>
        <WorkingFolder>CodePackage</WorkingFolder>
      </ExeHost>
    </SetupEntryPoint>

    <EntryPoint>
      <ExeHost>
        <Program>VotingWeb.exe</Program>
        <WorkingFolder>CodePackage</WorkingFolder>
      </ExeHost>
    </EntryPoint>
  </CodePackage>

  <ConfigPackage Name="Config" Version="1.0.0" />

  <Resources>
    <Endpoints>
      <Endpoint Protocol="https" Name="EndpointHttps" Type="Input" Port="443" />
    </Endpoints>
  </Resources>
</ServiceManifest>

添加批处理和 PowerShell 设置脚本Add the batch and PowerShell setup scripts

若要从 SetupEntryPoint 点运行 PowerShell,可以在指向 PowerShell 文件的批处理文件中运行 PowerShell.exe。To run PowerShell from the SetupEntryPoint point, you can run PowerShell.exe in a batch file that points to a PowerShell file. 首先,添加服务项目的批处理文件。First, add the batch file the service project. 在“解决方案资源管理器”中,右键单击“VotingWeb”,选择“添加”->“新建项”,然后添加名为“Setup.bat”的新文件。 In Solution Explorer, right-click VotingWeb and select Add->New Item and add a new file named "Setup.bat". 编辑 Setup.bat 文件,添加以下命令:Edit the Setup.bat file and add the following command:

powershell.exe -ExecutionPolicy Bypass -Command ".\SetCertAccess.ps1"

修改 Setup.bat 文件属性,将“复制到输出目录”设置为“如果较新则复制”。 Modify the Setup.bat file properties to set Copy to Output Directory to "Copy if newer".

设置文件属性

在“解决方案资源管理器”中,右键单击“VotingWeb”,选择“添加”->“新建项”,然后添加名为“SetCertAccess.ps1”的新文件。 In Solution Explorer, right-click VotingWeb and select Add->New Item and add a new file named "SetCertAccess.ps1". 编辑 SetCertAccess.ps1 文件,添加以下脚本:Edit the SetCertAccess.ps1 file and add the following script:

$subject="mytestcert"
$userGroup="NETWORK SERVICE"

Write-Host "Checking permissions to certificate $subject.." -ForegroundColor DarkCyan

$cert = (gci Cert:\LocalMachine\My\ | where { $_.Subject.Contains($subject) })[-1]

if ($cert -eq $null)
{
    $message="Certificate with subject:"+$subject+" does not exist at Cert:\LocalMachine\My\"
    Write-Host $message -ForegroundColor Red
    exit 1;
}elseif($cert.HasPrivateKey -eq $false){
    $message="Certificate with subject:"+$subject+" does not have a private key"
    Write-Host $message -ForegroundColor Red
    exit 1;
}else
{
    $keyName=$cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName

    $keyPath = "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\"
    $fullPath=$keyPath+$keyName
    $acl=(Get-Item $fullPath).GetAccessControl('Access')


    $hasPermissionsAlready = ($acl.Access | where {$_.IdentityReference.Value.Contains($userGroup.ToUpperInvariant()) -and $_.FileSystemRights -eq [System.Security.AccessControl.FileSystemRights]::FullControl}).Count -eq 1

    if ($hasPermissionsAlready){
        Write-Host "Account $userGroup already has permissions to certificate '$subject'." -ForegroundColor Green
        return $false;
    } else {
        Write-Host "Need add permissions to '$subject' certificate..." -ForegroundColor DarkYellow

        $permission=$userGroup,"Full","Allow"
        $accessRule=new-object System.Security.AccessControl.FileSystemAccessRule $permission
        $acl.AddAccessRule($accessRule)
        Set-Acl $fullPath $acl

        Write-Output "Permissions were added"

        return $true;
    }
}

修改 SetCertAccess.ps1 文件属性,将“复制到输出目录”设置为“如果较新则复制”。 Modify the SetCertAccess.ps1 file properties to set Copy to Output Directory to "Copy if newer".

以管理员身份运行设置脚本Run the setup script as a local administrator

默认情况下,服务设置入口点可执行文件运行时使用的凭据与 Service Fabric (通常为 NetworkService 帐户)使用的相同。By default, the service setup entry point executable runs under the same credentials as Service Fabric (typically the NetworkService account). SetCertAccess.ps1 需要管理员特权。The SetCertAccess.ps1 requires administrator privileges. 在应用程序清单中,可以将安全权限更改为在本地管理员帐户下运行启动脚本。In the application manifest, you can change the security permissions to run the startup script under a local administrator account.

在“解决方案资源管理器”中,打开 Voting/ApplicationPackageRoot/ApplicationManifest.xmlIn Solution Explorer, open Voting/ApplicationPackageRoot/ApplicationManifest.xml. 首先创建 Principals 节,然后添加新用户(例如,“SetupAdminUser”)。First, create a Principals section and add a new user (for example, "SetupAdminUser". 向 Administrators 系统组添加 SetupAdminUser 用户帐户。Add the SetupAdminUser user account to the Administrators system group. 接下来,在 VotingWebPkg ServiceManifestImport 节中配置 RunAsPolicy,以便向设置入口点应用 SetupAdminUser 主体。Next, in the VotingWebPkg ServiceManifestImport section, configure a RunAsPolicy to apply the SetupAdminUser principal to the setup entry point. 此策略告知 Service Fabric,Setup.bat 文件以 SetupAdminUser 身份(具有管理员特权)运行。This policy tells Service Fabric that the Setup.bat file runs as SetupAdminUser (with administrator privileges).

<?xml version="1.0" encoding="utf-8"?>
<ApplicationManifest xmlns:xsd="https://www.w3.org/2001/XMLSchema" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" ApplicationTypeName="VotingType" ApplicationTypeVersion="1.0.0" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <Parameters>
    <Parameter Name="VotingData_MinReplicaSetSize" DefaultValue="3" />
    <Parameter Name="VotingData_PartitionCount" DefaultValue="1" />
    <Parameter Name="VotingData_TargetReplicaSetSize" DefaultValue="3" />
    <Parameter Name="VotingWeb_InstanceCount" DefaultValue="-1" />
  </Parameters>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="VotingDataPkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="VotingWebPkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
    <Policies>
      <RunAsPolicy CodePackageRef="Code" UserRef="SetupAdminUser" EntryPointType="Setup" />
    </Policies>
  </ServiceManifestImport>
  <DefaultServices>
    <Service Name="VotingData">
      <StatefulService ServiceTypeName="VotingDataType" TargetReplicaSetSize="[VotingData_TargetReplicaSetSize]" MinReplicaSetSize="[VotingData_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[VotingData_PartitionCount]" LowKey="0" HighKey="25" />
      </StatefulService>
    </Service>
    <Service Name="VotingWeb" ServicePackageActivationMode="ExclusiveProcess">
      <StatelessService ServiceTypeName="VotingWebType" InstanceCount="[VotingWeb_InstanceCount]">
        <SingletonPartition />
      </StatelessService>
    </Service>
  </DefaultServices>
  <Principals>
    <Users>
      <User Name="SetupAdminUser">
        <MemberOf>
          <SystemGroup Name="Administrators" />
        </MemberOf>
      </User>
    </Users>
  </Principals>
</ApplicationManifest>

在本地运行应用程序Run the application locally

在“解决方案资源管理器”中,选择 Voting 应用程序并将“应用程序 URL” 属性设置为“https://localhost:443”。In Solution Explorer, select the Voting application and set the Application URL property to "https://localhost:443".

保存所有文件并按 F5,以便在本地运行应用程序。Save all files and hit F5 to run the application locally. 在应用程序部署完以后,Web 浏览器会打开到 https://localhost:443。After the application deploys, a web browser opens to https://localhost:443. 如果使用自签名证书,则会看到一个警告,指出电脑不信任此网站的安全性。If you are using a self-signed certificate, you see a warning that your PC doesn't trust this website's security. 转到该网页。Continue on to the web page.

Voting 应用程序

在群集节点上安装证书Install certificate on cluster nodes

在将应用程序部署到 Azure 之前,请将证书安装到所有远程群集节点的 Cert:\LocalMachine\My 存储中。Before deploying the application to the Azure, install the certificate into the Cert:\LocalMachine\My store of all the remote cluster nodes. 服务可以移到群集的不同节点。Services can move to different nodes of the cluster. 当前端 Web 服务在群集节点上启动时,启动脚本会查找证书并配置访问权限。When the front-end web service starts on a cluster node, the startup script will lookup the certificate and configure access permissions.

首先,将证书导出到 PFX 文件。First, export the certificate to a PFX file. 打开 certlm.msc 应用程序,导航到“个人” > “证书”。Open the certlm.msc application and navigate to Personal>Certificates. 右键单击 mytestcert 证书,选择“所有任务” > “导出”。Right-click on the mytestcert certificate, and select All Tasks>Export.

导出证书

在导出向导中,选择“是,导出私钥”,然后选择“个人信息交换(PFX)”格式。 In the export wizard, choose Yes, export the private key and choose the Personal Information Exchange (PFX) format. 将文件导出到 C:\Users\sfuser\votingappcert.pfxExport the file to C:\Users\sfuser\votingappcert.pfx.

接下来,使用 Add-AzServiceFabricApplicationCertificate cmdlet 在远程群集上安装证书。Next, install the certificate on the remote cluster using the Add-AzServiceFabricApplicationCertificate cmdlet.

警告

对于开发和测试应用程序,自签名证书已足够。A self-signed certificate is sufficient for development and testing applications. 对于生产应用程序,请使用证书颁发机构 (CA) 提供的证书,而不是自签名证书。For production applications, use a certificate from a certificate authority (CA) instead of a self-signed certificate.

Connect-AzAccount

$vaultname="sftestvault"
$certname="VotingAppPFX"
$certpw="!Password321#"
$groupname="voting_RG"
$clustername = "votinghttps"
$ExistingPfxFilePath="C:\Users\sfuser\votingappcert.pfx"

$appcertpwd = ConvertTo-SecureString -String $certpw -AsPlainText -Force

Write-Host "Reading pfx file from $ExistingPfxFilePath"
$cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 $ExistingPfxFilePath, $certpw

$bytes = [System.IO.File]::ReadAllBytes($ExistingPfxFilePath)
$base64 = [System.Convert]::ToBase64String($bytes)

$jsonBlob = @{
   data = $base64
   dataType = 'pfx'
   password = $certpw
   } | ConvertTo-Json

$contentbytes = [System.Text.Encoding]::UTF8.GetBytes($jsonBlob)
$content = [System.Convert]::ToBase64String($contentbytes)

$secretValue = ConvertTo-SecureString -String $content -AsPlainText -Force

# Upload the certificate to the key vault as a secret
Write-Host "Writing secret to $certname in vault $vaultname"
$secret = Set-AzureKeyVaultSecret -VaultName $vaultname -Name $certname -SecretValue $secretValue

# Add a certificate to all the VMs in the cluster.
Add-AzServiceFabricApplicationCertificate -ResourceGroupName $groupname -Name $clustername -SecretIdentifier $secret.Id -Verbose

在 Azure 负载均衡器中打开端口 443Open port 443 in the Azure load balancer

在负载均衡器中打开端口 443(如果尚未打开)。Open port 443 in the load balancer if it isn't already.

$probename = "AppPortProbe6"
$rulename="AppPortLBRule6"
$RGname="voting_RG"
$port=443

# Get the load balancer resource
$resource = Get-AzResource | Where {$_.ResourceGroupName –eq $RGname -and $_.ResourceType -eq "Microsoft.Network/loadBalancers"}
$slb = Get-AzLoadBalancer -Name $resource.Name -ResourceGroupName $RGname

# Add a new probe configuration to the load balancer
$slb | Add-AzLoadBalancerProbeConfig -Name $probename -Protocol Tcp -Port $port -IntervalInSeconds 15 -ProbeCount 2

# Add rule configuration to the load balancer
$probe = Get-AzLoadBalancerProbeConfig -Name $probename -LoadBalancer $slb
$slb | Add-AzLoadBalancerRuleConfig -Name $rulename -BackendAddressPool $slb.BackendAddressPools[0] -FrontendIpConfiguration $slb.FrontendIpConfigurations[0] -Probe $probe -Protocol Tcp -FrontendPort $port -BackendPort $port

# Set the goal state for the load balancer
$slb | Set-AzLoadBalancer

将应用程序部署到 AzureDeploy the application to Azure

保存所有文件,从“调试”切换到“发布”,然后按 F6 进行重新生成。Save all files, switch from Debug to Release, and hit F6 to rebuild. 在“解决方案资源管理器”中,右键单击“Voting”并选择“发布” 。In Solution Explorer, right-click on Voting and select Publish. 选择在将应用程序部署到群集中创建的群集的连接终结点,或者选择另一群集。Select the connection endpoint of the cluster created in Deploy an application to a cluster, or select another cluster. 单击“发布”,将应用程序发布到远程群集。 Click Publish to publish the application to the remote cluster.

当应用程序部署后,打开 Web 浏览器,导航到 https://mycluster.region.cloudapp.azure.com:443(使用群集的连接终结点更新 URL)。When the application deploys, open a web browser and navigate to https://mycluster.region.cloudapp.azure.com:443 (update the URL with the connection endpoint for your cluster). 如果使用自签名证书,则会看到一个警告,指出电脑不信任此网站的安全性。If you are using a self-signed certificate, you see a warning that your PC doesn't trust this website's security. 转到该网页。Continue on to the web page.

Voting 应用程序

后续步骤Next steps

本教程的此部分介绍了如何:In this part of the tutorial, you learned how to:

  • 在服务中定义一个 HTTPS 终结点Define an HTTPS endpoint in the service
  • 将 Kestrel 配置为使用 HTTPSConfigure Kestrel to use HTTPS
  • 在远程群集节点上安装 SSL 证书Install the SSL certificate on the remote cluster nodes
  • 允许 NETWORK SERVICE 访问证书的私钥Give NETWORK SERVICE access to the certificate's private key
  • 在 Azure 负载均衡器中打开端口 443Open port 443 in the Azure load balancer
  • 将应用程序部署到远程群集Deploy the application to a remote cluster

转到下一教程:Advance to the next tutorial: