How to force a .NET website to use TLS 1.2

Posted written by Paul Seal on March 25, 2018 .NET Framework

With TLS 1.0 and 1.1 being depricated, you will no doubt need to force your .NET websites / services to run over TLS 1.2 

This blog post shows you how you can do that.

NOTE: Thanks to @cultiv on Twitter for pointing this out. You can't force a site to respond only on TLS 1.2 this way, you would have to disable the other versions on the server to do that. What we are doing here is forcing all outgoing connections to TLS 1.2 first (it still falls back to 1.1/1.0 if the remote doesn't support 1.2).

MVC and Web API

In the root of the site, find the global.asax file, right click on it and view code.

In this file, there should be an Application_Start method.

In this method, add these lines to force TLS 1.2

namespace YourApplication
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //**Add these lines**
            if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Tls12) == false)
            {
                ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;
            }
            //**Add these lines**

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Umbraco

If you are using Umbraco, you can put it in the ApplicationStarted method in a class which inherits from IApplicationEventHandler like this:

namespace YourApplication.EventHandlers
{
    public class RegisterEvents : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Tls12) == false)
            {
                ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;
            }
        }
    }
}