How can I configure wcf web api service for HTTPS transport? Does anyone know how much this wi开发者_如何转开发ll change in the final release since this is one of the areas they say will change?
To support HTTPS you will need to enable transport security on the HttpBinding. This can be done by deriving from the HttpConfigurableServiceHostFactory and override the CreateServiceHost like this:
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;
}
}
Finally the HypertextTransferProtocolSecureServiceHostFactory must be added to the RouteTable:
RouteTable.Routes.Add(new ServiceRoute("routePrefix", new HypertextTransferProtocolSecureServiceHostFactory(), typeof(ServiceType)));
In our latest drop you can set the binding without creating a new host by using the HttpConfiguration object. It exposes a SetSecurity method you can set to change the security mode.
Here is my configuration from the Global.asax, I check the URI and then use the correct mode. Works well in IIS and IIS Express. . . . my goal is Basic over HTTPS, however IIS express keeps the HTTP URI in the "binding" and unless you deal with it you get suck in an endless loop (http://screencast.com/t/kHvM49dl6tP, http://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))
};
精彩评论