Bind certificate in .NET Framework + Topshelf + C#

79 Views Asked by At

I have an API as a Windows service and I need to bind the certificate to the Windows service so that the API is available over https (ssl).

Please remember that I need this in .NET Framework.

Firstly do I need to write the code in program.cs or startup.us? Please find the code for each shown here.

Current code in program.cs:

    static void Main(string[] args)
    {
        _logger = LogFactory.GetLogger<Program>();
        loadCertificates();
        _logger.Info("Main: Starting...");

        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

        _container = DependencyConfig.Configure();

        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        const string CnName = "test.lab.local";

        X509Certificate2Collection currentcerts = store.Certificates.Find(X509FindType.FindBySubjectName, CnName, false);

        store.Close();

        X509Certificate2 certdata = currentcerts[0];

        HostFactory.Run(c =>
            {
                c.RunAsLocalService();
                c.SetDescription(ServiceDescription);
                c.SetDisplayName(DisplayName);
                c.SetServiceName(ServiceName);
             });
    }

Startup.cs

public void Configuration(IAppBuilder app)
{
    app.UseApplicationInsights(null, new OperationIdContextMiddlewareConfiguration { OperationIdFactory = IdFactory.FromHeader() });

    HttpConfiguration config = new HttpConfiguration
        {
            DependencyResolver = new MefDependencyResolver(DependencyConfig.Configure())
        };

    config.MapHttpAttributeRoutes(); 

    bool useTls = Convert.ToBoolean(ConfigurationManager.AppSettings["UseTls"].Trim());

    app.UseRequireTls(useTls);
    app.RestoreOperationIdContext();
    app.UseWebApi(config);
}

I was trying to bind the certificate fetched and add it to the application so that the API is exposed using https.

I am unable to find a way to add the certificate using the HostFactory.Run or IAppBuilder. Can someone please help me?

0

There are 0 best solutions below