Software Developer, Technology Enthusiast, Retro and Husband and Dad based in Melbourne.

Monthly Archives: August 2014

Simple 301 Redirect for ASP.NET

A 301 Redirect is a way of sending search engines and user traffic to a specific? URL ,? also telling the search engines to do a permanently move on? that URL.

Implementing 301 redirect in ASP.NET Webforms or ASP.NET MVC; Simply use the Application_BeginRequest event in Global.asax. Then retrieve the URL from the Web.Config file or a Repository.

protected void Application_BeginRequest(Object sender, EventArgs e)
{
string path = "";
switch (Request.Url.Scheme)
{

case "https":
Response.AddHeader("Strict-Transport-Security", "max-age=300");
break;
case "http":
    if (Request.Url.PathAndQuery == "/")
     {

    path = "https://" + WebUtils.WebConfigUtils.GetAppSettingskey("SiteURL") + "/";

    }
else
    {
     path = "https://" + WebUtils.WebConfigUtils.GetAppSettingskey("SiteURL") + "/" + Request.Url.PathAndQuery;

    }
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location", path);
    break;
   }
}

  • When a URL request for an http is made, the switch statement responses by inserting a 301 Moved Permanently and the new location path into the HTTP header .
  • Store the SiteURL in the Web.Config or a Repository.
  • When a URL request for an https is made,the switch statement responses by in inserting Strict-Transport-Security telling the browser to prevent any communications from being sent for HTTP.

Test this function locally in your development environment use IIS Express SSL option.?

References

301 Moved Permanently
http://moz.com/learn/seo/redirection

HTTP Strict Transport Security
https://www.owasp.org/index.php/HTTP_Strict_Transport_Security

Global.asax
http://msdn.microsoft.com/en-us/library/1xaas8a2%28v=vs.71%29.aspx

NovusCodeLibrary.NET – Utilities Library for .NET
https://github.com/novuslogic/NovuscodeLibrary.NET

Working with SSL at Development Time is easier with IISExpress
Working with SSL at Development Time is easier with IISExpress