WCF Web API安全性

Dar*_*rth 3 wcf wcf-web-api

如何为HTTPS传输配置wcf web api服务?有谁知道这会在最终版本中发生多大变化,因为这是他们说会改变的领域之一?

小智 6

要支持HTTPS,您需要在HttpBinding上启用传输安全性.这可以通过从HttpConfigurableServiceHostFactory派生并覆盖CreateServiceHost来完成:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,必须将HypertextTransferProtocolSecureServiceHostFactory添加到RouteTable:

RouteTable.Routes.Add(new ServiceRoute("routePrefix", new HypertextTransferProtocolSecureServiceHostFactory(), typeof(ServiceType)));
Run Code Online (Sandbox Code Playgroud)


Gle*_*ock 5

在我们最新的drop中,您可以使用HttpConfiguration对象设置绑定而无需创建新主机.它公开了一个SetSecurity方法,您可以设置该方法来更改安全模式.