In this Video, I am going to discuss How to enable HTTPS in Web API Service with an example. In our previous Video, we discussed how to enable SSL in Visual Studio Development Server. Please read our previous Video before proceeding to this Video as we are going to work with the same example that we worked in our previous Video.

At the moment, we can use both the HTTP and HTTPS to invoke the Web API resources as shown below and both the URI will give you the same result.
http://localhost:55486/api/employees
https://localhost:44300/api/employees
In this Video, we are going to discuss how to enable HTTPS in Web API Service means once we enabled the HTTPS, if a request is issued using the HTTP then we want that request to be automatically redirected to HTTPS.
Point to Remember: If you are coming from the ASP.NET MVC background, then you may be tempted to use the built-in RequireHttpsAttribute but the sad thing is that this attribute is not supported in Web API.
How to enable HTTPS in Web API Service?
You need to follow the below two steps to enable HTTPS in Web API.
Step1:
Right click on the Models Folder and add a class file with the name CustomRequireHttpsAttribute and then copy and paste the following code.
Step2:
You need to register the CustomRequireHttpsAttribute in the Register() method of the WebApiConfig class in WebApiConfig.cs file which is present in the App_Start folder as shown below.
The above line of code will add the CustomRequireHttpsAttribute as a global filter to the filters collection as a result for every incoming request the code which is present in this filter is going to be executed. So, if the request is issued using HTTP, then it will be automatically redirected to HTTPS.
The complete code of the WebApiConfig.cs file is given below.
Now, build the solution and navigate to the following URL.
http://localhost:55486/api/employees
Once you hit the browser you will see that the above URL is transmitted to the below URL
https://localhost:44300/api/employees
Note: If you dont want to enable the HTTPS for the entire application, then dont add the CustomRequireHttpsAttribute to the filters collection on the config object in the register method of the WebApiConfig class.
What you need to do is, decorate the controller class or the action method with CustomRequireHttpsAttribute for which you want the HTTPS to be enabled. For the rest of the controllers and action methods, HTTPS will not be enabled.