Created
September 12, 2013 01:07
-
-
Save bjcull/6532040 to your computer and use it in GitHub Desktop.
Dynamically creates https endpoints for Configurationless WCF (Restful)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HttpsWebServiceHostFactory : WebServiceHostFactory | |
{ | |
protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) | |
{ | |
WebServiceHost host = new WebServiceHost(serviceType, baseAddresses); | |
foreach (Uri baseAddress in baseAddresses) | |
{ | |
WebHttpBinding binding = CreateRestBinding(baseAddress); | |
ServiceEndpoint endpoint = host.AddServiceEndpoint(serviceType.GetInterfaces()[0], binding, baseAddress); | |
} | |
if (HasHttpEndpoint(baseAddresses)) | |
{ | |
if (host.Description.Behaviors.Contains(typeof(ServiceMetadataBehavior))) | |
{ | |
var smb = (ServiceMetadataBehavior)host.Description.Behaviors[typeof(ServiceMetadataBehavior)]; | |
smb.HttpGetEnabled = true; | |
} | |
else | |
{ | |
var smb = new ServiceMetadataBehavior(); | |
smb.HttpGetEnabled = true; | |
host.Description.Behaviors.Add(smb); | |
} | |
} | |
if (HasHttpsEndpoint(baseAddresses)) | |
{ | |
if (host.Description.Behaviors.Contains(typeof(ServiceMetadataBehavior))) | |
{ | |
var smb = (ServiceMetadataBehavior)host.Description.Behaviors[typeof(ServiceMetadataBehavior)]; | |
smb.HttpsGetEnabled = true; | |
} | |
else | |
{ | |
var smb = new ServiceMetadataBehavior(); | |
smb.HttpsGetEnabled = true; | |
host.Description.Behaviors.Add(smb); | |
} | |
} | |
return host; | |
} | |
private bool HasHttpsEndpoint(Uri[] baseAddresses) | |
{ | |
return baseAddresses.Any(b => b.Scheme == Uri.UriSchemeHttps); | |
} | |
private bool HasHttpEndpoint(Uri[] baseAddresses) | |
{ | |
return baseAddresses.Any(b => b.Scheme == Uri.UriSchemeHttp); | |
} | |
private WebHttpBinding CreateRestBinding(Uri baseAddress) | |
{ | |
WebHttpBinding binding; | |
if (baseAddress.Scheme == Uri.UriSchemeHttps) | |
{ | |
binding = new WebHttpBinding(WebHttpSecurityMode.Transport); | |
} | |
else | |
{ | |
binding = new WebHttpBinding(); | |
} | |
binding.CrossDomainScriptAccessEnabled = true; | |
return binding; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment