2011-07-05 108 views
3

如何爲HTTPS傳輸配置wcf web api服務? 有誰知道這會在最終版本中發生多大的變化,因爲這是他們說會改變的領域之一?WCF Web API安全

回答

6

要支持HTTPS,您需要啓用HttpBinding上的傳輸安全性。

public class HypertextTransferProtocolSecureServiceHostFactory : HttpConfigurableServiceHostFactory 
{ 
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) 
    { 
     var configurationBuilder = HttpHostConfiguration.Create(); 

     var host = new HttpConfigurableServiceHost(serviceType, configurationBuilder, baseAddresses); 

     foreach (var endpoint in host.Description.Endpoints.Where(e => e.ListenUri.Scheme == "https")) 
     { 
      var binding = endpoint.Binding as HttpBinding; 

      if (binding != null) 
      { 
       binding.Security.Mode = HttpBindingSecurityMode.Transport; 
      } 
     } 
     return host; 
    } 
} 

最後HypertextTransferProtocolSecureServiceHostFactory必須添加到RouteTable:這可以通過從HttpConfigurableServiceHostFactory派生並重寫CreateServiceHost這樣做

RouteTable.Routes.Add(new ServiceRoute("routePrefix", new HypertextTransferProtocolSecureServiceHostFactory(), typeof(ServiceType))); 
+0

非常感謝該hskan: >} – Darth

5

在我們最新的下降可以設置沒有結合通過使用HttpConfiguration對象創建一個新的主機。它公開了您可以設置更改安全模式的SetSecurity方法。

+0

Glenn有沒有這個地方的例子?我正在努力重新配置Web API服務以通過https工作。 –

2

這是我從Global.asax的配置,我檢查了URI並使用了正確的模式。在IIS和IIS Express中運行良好。 。 。 。我的目標是基本通過HTTPS,但是IIS快遞保持HTTP URI中的「結合」,除非你處理它,你在無限循環(http://screencast.com/t/kHvM49dl6tPhttp://screencast.com/t/5usIEy5jgPdX)得到吸

   var config = new HttpConfiguration 
         { 
          EnableTestClient = true, 
          IncludeExceptionDetail = true, 
          EnableHelpPage = true, 
          Security = (uri, binding) => 
              { 
               if (uri.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase)) 
                binding.Mode = HttpBindingSecurityMode.Transport; 
               else 
                binding.Mode = HttpBindingSecurityMode.TransportCredentialOnly; 

               binding.Transport.ClientCredentialType = HttpClientCredentialType.Basic; 
              }, 
          CreateInstance = ((t, i, h) => container.Resolve(t)) 
         };