This article is to show you how to add SSL to Self-Hosted Web Api
Maybe some of the people don’t like IIS. IIS comes with all the Windows and handle many technical operation so as a developer, we can focus on the core competency of the business.
For those people who want to implement SSL in self-hosted Web Api that is what I found out after reading blogs and msdn.
1. Create a class file inherit from HttpSelfHostConfiguration.
internal class EExtendHttpSelfHostConfigurationpublic : HttpSelfHostConfiguration
{
public EExtendHttpSelfHostConfigurationpublic(string baseAddress)
: base(baseAddress)
{
}
protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
{
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
return base.OnConfigureBinding(httpBinding);
}
}
2. Put this code in main program.
private static void Main()
{
string sslAddress = “https://127.0.0.1:4443/”;
var config = new EExtendHttpSelfHostConfigurationpublic(sslAddress);
//Need tp refactor to use the route in Startup.cs
config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine(“Press Enter to quit.”);
Console.ReadLine();
}
}
The sample way for you is download the sample from http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api then modify it.
This is not end yet. You need to add the SSL certification, generate a certificate from IIS if you do not have one, using netsh command. Go to command prompt and type the below.
netsh http add urlacl url=https://+:4443/ user=Everyone
netsh http add sslcert ipport=0.0.0.0:4443 certhash=5dc0ca6239d24e1419ec68502c92afef5756f886 appid={1EA348FB-F83E-4AC8-B909-372BBA9B08E9}
Do not follow exactly, you should have your certhash from your own certificate. You can also generate another guid from Visual Studio for appid.
You can now run the application.
You can also download a single solution from http://skydrive.live.com. The sample file name is OwinSelfhostSample.zip My MSN ID is chanmmn@hotmail.com.
Hi, do you still have the sample somewhere? Cheers, Bjorn
Try to download the sample here https://1drv.ms/u/s!AuZYHSwsevw1ojx2NIgmUp5fdcA_?e=XfkV7e.
Thanks! 🙂 Do you know if its any difference between WebApp HttpSelfHostServer?
We use
webApp = WebApp.Start(url);
Your example use:
server = new HttpSelfHostServer(config)
Where the Startup class very much look like your config settings.