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

ASP.NET MVC

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

Encoding a ASP.NET MVC 4 Model for Javascript within a Razor Page

Sometimes you want to pass a property of a model to a Javascript variable, by encoding an ASP.NET 4 model into a Javascript variable, ?using ?HTML Helper and a strongly-typed model within a Razor Page. Razor Page

Razor Page

@model MyWebApp.Models.Foo
@{
ViewBag.Title = "Foo";
}

<script type="text/javascript">
var _model = @Html.Raw(Json.Encode(Model))
</script>
@Scripts.Render("/scripts/Foo.js")

 

  • The model must be strongly-typed.
  • Model encoding must be done at the top of the Razor page to allow the encoded JSON variable to be accessible.
  • JQuery must be included.

 

Example output

<script type="text/javascript">
var _model = {"Firstname":"Adam","Lastname":"Johnston"}
</script>

_model.Firstname
_model.Lastname