How to Redirect URLs/domain Without www to With www and Vice versa - Permanent Redirection in ASP.Net.
Search engines like Google will treat a page with url http://www.yourdomain.com/Default.aspx as different from http:// yourdomain.com/Default.aspx even though they are serving the same page on a website. Hence, there are chances that Google may penalise your website with Duplicate Content violations or your page rank will be affected. We can prevent this by redirecting users/user agents by sending a 301 status code to the url with www prefix if they are accessing without www.
For an ASP.Net application, we can use the Application_BeginRequest event in Global.asax event and Response object to do a permanent redirection with "301 Moved permanently" status code.
The below code help you to do that,
void Application_BeginRequest(object sender, EventArgs e)
string FromHomeURL = http:// yourdomain.com;
string ToHomeURL = http:// www.yourdomain.com;
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));
The above code will put a www prefix if you try to access the website without www i.e like http:// yourdomain.com.