• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Thursday, July 16, 2020

Enable HTTPS in Web API Service

 Admin     July 16, 2020     .Net, Asp.Net, C#, Web API     No comments   

In this article, I am going to discuss How to enable HTTPS in Web API Service with an example. In our previous article, we discussed how to enable SSL in the 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.

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.

Summary:
I hope this post will be helpful to enable HTTPS in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • Cascading referential integrity constraint in Sql Server
    Hi friends! In our previous sessions we have seen how to create tables and enforce primary and foreign key constraints between them . And in...
  • Navigation Menus in ASP.NET Core
    In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. P...
  • ASP.NET Core Middleware Components
    In this article, I am going to discuss the ASP.NET Core Middleware Components in detail. Please read our previous article before proceedin...
  • Creating and Working with Database
    Hi friends! In our last post we have seen different approaches how we can connect with SQL Server Management Studio(SSMS). Today, We are g...
  • HMAC Authentication in Web API
    In this article, I am going to discuss how to implement the HMAC Authentication in Web API Application. Please read our previous article w...
  • Usability of SecureString object in C#
    Introduction Hi friends! In this blog we will be discussing a very interesting as well as useful topic in C# and that is Securestring objec...
  • Connecting to SQL Server using SSMS
    Introduction Hi friends! In this blog we will be discussing How to connect to the SQL Server using SQL Server Management Studio (SSMS). ...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape