• 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

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

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