I am trying to implement URL redirect for the website rather than doing it page by page. I want to do it in the global.asax file. Below is the code i have defined.
I
if you didn't know what is application domain name ,use something like this
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).Contains("localhost"))return;
var leftPartOfUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).ToLower();
if (leftPartOfUrl.StartsWith("http") && leftPartOfUrl.Split('.').Length == 1)
{
var fullUrl = HttpContext.Current.Request.Url.ToString();
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.StatusCode = 301;
HttpContext.Current.Response.AddHeader("Location", fullUrl.Insert(fullUrl.IndexOf("://", StringComparison.Ordinal) + 3, "www."));
HttpContext.Current.Response.End();
}
}