Reputation: 29659
I want to redirect to a page that and force https:
e.g
Response.Redirect("~/Login.aspx");
I want to redirect to
https://myserver/Login.aspx
how can i force https?
Upvotes: 4
Views: 6333
Reputation: 4155
I like to call this method from Page_Load in any page where I want to force https. Specifically, from any page where the user may enter a password, such as login, registration, and password reset pages.
protected void ForceHTTPS()
{
string serverName = Request.ServerVariables["SERVER_NAME"];
string pagePath = Page.AppRelativeVirtualPath.Replace("~", "");
string queryString = Request.Url.Query;
if (serverName != "localhost" && !Request.IsSecureConnection)
{
Response.Redirect("https://" + SECURE_DOMAIN + pagePath + queryString);
}
}
The reason I use a pre-defined constant for SECURE_DOMAIN rather than just reading it out of the Request.ServerVariables["SERVER_NAME"] is that our SSL certificate only works if there is a "www." on the beginning of the domain name, so I want to make sure to force that domain name too in case the user has browsed to the site using the domain name without the www., or potentially used some other domain name alias.
And I do not do the redirect if the server name is "localhost" so that the code also works in my development environment when run from Visual Studio.
Upvotes: 1
Reputation: 29659
Thanks Silky for starting me off.
I've ended up with
var url = String.Format("https://{0}{1}",
Request.ServerVariables["HTTP_HOST"] ,
ResolveUrl("~/Login.aspx"));
Response.Redirect(url);
Upvotes: 5