Enable HTTPS in Web API

Enable HTTPS in Web API

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

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 article, 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.

using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebAPIEnableHTTPS.Models
{
    public class CustomRequireHttpsAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //both the request is not https
            if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Found);
                actionContext.Response.Content = new StringContent
                    ("<p>Use https instead of http</p>", Encoding.UTF8, "text/html");

                //Create the request URI
                UriBuilder uriBuilder = new UriBuilder(actionContext.Request.RequestUri);

                //Set the Request scheme as HTTPS
                uriBuilder.Scheme = Uri.UriSchemeHttps;

                //Set the HTTPS Port number as 44300
                //In the project properties window you can find the port number
                //for SSL URL
                uriBuilder.Port = 44300;
                actionContext.Response.Headers.Location = uriBuilder.Uri;
            }
            else
            {
                base.OnAuthorization(actionContext);
            }
        }
    }
}
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.

How to enable HTTPS in Web API

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.

using System.Web.Http;
using WebAPIEnableHTTPS.Models;

namespace WebAPIEnableHTTPS
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Filters.Add(new CustomRequireHttpsAttribute());
            
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

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 don’t want to enable the HTTPS for the entire application, then don’t 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. 

SUMMARY

In this article, I try to explain How to enable HTTPS in Web API with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

No HTML was returned.

Leave a Reply

Your email address will not be published. Required fields are marked *