browse by category or date

As we all know, HTTP is not secure. It is easy for evil people to listen the HTTP conversation between client and server. If our application is using AJAX to send/retrieve data from server, we are at a high risk.

No other methods can prevent the Man-In-The-Middle attack, except HTTPS protocol.

To do so, we need to ensure that people is using HTTPS protocol instead of HTTP.

I will share with you the solution that I did to make the Web Application automatically redirect to the HTTPS protocol.

First Step: Create App_Code folder in your ASP.NET web root
Second Step: Create the redirect class

RedirectHttpModule.cs

using System;
using System.Web;

namespace myMVCProject.App_Code
{
    public class RedirectHttpModule: IHttpModule
    {
        public RedirectHttpModule()
        { }

        public String ModuleName
        {
            get { return "RedirectHttpModule"; }
        }

        public void Init(HttpApplication app)
        {
            app.BeginRequest += (new EventHandler(this.BeginRequest));
        }
        public void BeginRequest(Object source, EventArgs e)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext ctx = app.Context;
            if (ctx.Request.Url.OriginalString.ToLower().StartsWith("http://"))
            {
                
                 ctx.Response.Redirect("https://" + ctx.Request.Url.Host + ctx.Request.Url.LocalPath +  ctx.Request.Url.Query);
            }
        }
        public void Dispose()
        {
        }
    }
}

Third Step: Modify your web.config

...
      
        ...
               
        ...

...

I hope it helps 😉

GD Star Rating
loading...
How To Automatically Redirect HTTP to HTTPS Using .NET HttpModule, 4.0 out of 5 based on 1 rating

Possibly relevant:

About Hardono

Howdy! I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 11 years.

Incoming Search

.net, c#, iis

2 comments so far

Add Your Comment
  1. this is good code thanks

  2. its work for me, thanks for sharing