65.9K
CodeProject 正在变化。 阅读更多。
Home

WCF 自托管服务( 通过 HTTPS)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.71/5 (9投票s)

2010 年 11 月 26 日

CPOL

2分钟阅读

viewsIcon

96264

downloadIcon

5228

一份关于创建通过 HTTPS 的 WCF SOAP 服务的自托管服务的指南。

引言

通过本文,C# 程序员可以获得一种非常简单的方法来创建自托管的 WCF 服务,了解不同的 WCF 绑定,最重要的是,了解安装服务器证书并使用 HTTPS 运行 WCF 服务的逐步指南。

代码

首先,我们将处理创建托管 WCF Web 服务的 Windows 服务以及设置 WCF 所需配置的过程。在 Visual Studio 中创建一个 Windows 服务项目,然后使用“添加项”添加一个 Installer 类。添加 GetServiceProcessInstaller 方法,您可以在其中指定 Windows 服务将安装在哪个帐户下。然后,添加 GetServiceInstaller 方法,您需要在其中指定 Windows 服务的 NameDescription

private static ServiceProcessInstaller GetServiceProcessInstaller()
{
    ServiceProcessInstaller installer = 
      new ServiceProcessInstaller { Account = ServiceAccount.LocalSystem };
    return installer;
}

private static ServiceInstaller GetServiceInstaller()
{
    Process pc = Process.GetCurrentProcess();
    Directory.SetCurrentDirectory
    (pc.MainModule.FileName.Substring(0, 
     pc.MainModule.FileName.LastIndexOf(@"\", 
     StringComparison.CurrentCulture)
    ));

    ServiceInstaller installer = new ServiceInstaller
    {
        ServiceName = "WCF Over Https",
        Description = "WCF Over Https"
    };

    return installer;
}

将以下两行代码放在 Installer 类构造函数中

Installers.Add(GetServiceInstaller());
Installers.Add(GetServiceProcessInstaller());

现在让我们创建 WCF 服务中需要的接口。此 WCF 服务将托管两种不同的绑定,一种 SOAP 绑定,另一种用于下载文件的 HTTP 绑定。

using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WCFOverHttps.WCFHost
{
    [ServiceContract(Namespace = "WCFOverHttps.WCFHost")]
    public interface IWcfHttpService
    {
        [OperationContract]
        [WebGet(UriTemplate = "GetFile/{path}")]
        Stream GetFile(string path);
    }
}

using System.ServiceModel;

namespace WCFOverHttps.WCFHost
{
    [ServiceContract(Namespace = "WCFOverHttps.WCFHost")]
    public interface IWcfSoapService
    {
        [OperationContract]
        string HelloWorld();
    }
}

一旦完成创建接口并指定将添加到 WCF 服务的所有方法,就可以编写服务的实际实现代码了。

using System;
using System.IO;
using System.ServiceModel.Web;

namespace WCFOverHttps.WCFHost
{
    public class WcfService : IWcfHttpService, IWcfSoapService
    {
        public string HelloWorld()
        {
            return "Hello World";
        }

        public Stream GetFile(string path)
        {
            path = string.Format("c:\\{0}", path);
            try
            {
                if (!File.Exists(path))
                    throw new Exception("File not found");

                if (WebOperationContext.Current != null)
                    WebOperationContext.Current.OutgoingResponse.ContentType = 
                       "application/octet-stream";

                return File.OpenRead(path);
            }
            catch (Exception ex)
            {
                if (WebOperationContext.Current != null)
                    WebOperationContext.Current.OutgoingResponse.
                         SetStatusAsNotFound(ex.Message);

                return null;
            }
        }
    }
}

完成 WCF 服务的最后一步是 ServiceModel 配置,因此只需使用“添加项”添加一个 应用程序配置文件,并在配置部分添加 system.ServiceModel 部分,我们将在其中配置所有终结点和安全设置。

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <bindings>
      <basicHttpBinding>
        <binding name ="soapBinding">
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </basicHttpBinding>
      <webHttpBinding>
        <binding name="httpBinding">
          <security mode="Transport">
            <transport clientCredentialType="None"/>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WCFOverHttps.WCFHost.WcfService"
               behaviorConfiguration="ServiceBehaviour">
        <host>
          <baseAddresses>
            <add baseAddress="https://192.168.0.2:81/WcfService"/>
          </baseAddresses>
        </host>
        <endpoint address=""
                  binding="basicHttpBinding"
                  bindingConfiguration="soapBinding"
                  contract="WCFOverHttps.WCFHost.IWcfSoapService" />
        <endpoint address="https://192.168.0.2:81/WcfService/http"
                  binding="webHttpBinding"
                  bindingConfiguration="httpBinding"
                  contract="WCFOverHttps.WCFHost.IWcfHttpService"
                  behaviorConfiguration="WebBehavior"/>
        <endpoint address="mex"
                binding="mexHttpsBinding"
                contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceDebug includeExceptionDetailInFaults="False"/>
          <serviceMetadata httpsGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
</system.serviceModel>

您可以在此配置部分自定义 WCF 服务的 URL 以及每个终结点的 URL。HTTPS 配置在绑定配置中找到:<security mode="Transport">

现在 Windows 服务已完成,我们可以使用命令 InstallUtil32(64).exe WCFOverHttps.exe 进行安装,但如果您现在测试它,它将无法工作,因为没有安装并授权用于 WCF 服务器的证书。因此,让我们安装一个证书颁发机构,然后使用它来创建和签署服务器证书

  1. 打开 Visual Studio 命令提示符。
  2. 创建证书颁发机构
  3. makecert.exe -sv SignRoot.pvk -cy authority -r 
      signroot.cer -a sha1 -n "CN=AuthorityName" 
      -ss my -sr localmachine
  4. 创建服务器证书
  5. makecert.exe -iv SignRoot.pvk -ic signroot.cer -cy 
      end -pe -n CN="localhost" -eku 1.3.6.1.5.5.7.3.1 -ss 
      my -sr localmachine -sky exchange 
      -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12

证书现在已安装,但我们需要将其映射到 WCF 服务配置文件中指定的端口(这里,我们有端口 81)。我们可以使用随附的 HttpConfig 实用程序来执行此操作。打开它并转到“SSL”选项卡,单击“添加”,输入 WCF 服务的 IP 地址、端口、在 AssemblyInfo 中找到的 Windows 服务的 GUID,然后“浏览”找到您刚刚创建的证书。单击“确定”然后单击“应用”,您的 WCF 服务现在应该可以通过安全的 HTTPS 正常工作了。

未来目标

找到一种使用嵌入式证书自托管 HTTPS WCF 服务的方法,以便可以轻松地将其移动到任何服务器。非常感谢任何建议。

© . All rights reserved.