Reputation: 146
I'm using OVH Server with SSL Gateway Free where i've hosted my MVC5 App.
When i was trying to force only HTTPS connection my browser displayed:
"ERR_TOO_MANY_REDIRECTS".
I was trying various things and solutions but none of them worked.
I enabled SSL in my project properties, tried to redirect through URL Rewrite on my IIS followed by this tutorial and many others, use [RequireHttps]
on my BaseController
and also a lots of configuration of Application_BeginRequest()
in Global.asax.
f.e.:
protected void Application_BeginRequest()
{
if (!Context.Request.IsSecureConnection)
{
// This is an insecure connection, so redirect to the secure version
UriBuilder uri = new UriBuilder(Context.Request.Url);
if (!uri.Host.Equals("localhost"))
{
uri.Port = 443;
uri.Scheme = "https";
Response.Redirect(uri.ToString());
}
}
}
Have no idea how to force only HTTPS connection.
Upvotes: 1
Views: 2538
Reputation: 146
@PeteG answer was right. IsSecureConnection isnt working all you have to do is to use this code:
protected void Application_BeginRequest()
{
var loadbalancerReceivedSslRequest = string.Equals(Request.Headers["X-Forwarded-Proto"], "https");
var serverReceivedSslRequest = Request.IsSecureConnection;
if (loadbalancerReceivedSslRequest || serverReceivedSslRequest) return;
UriBuilder uri = new UriBuilder(Context.Request.Url);
if (!uri.Host.Equals("localhost"))
{
uri.Port = 443;
uri.Scheme = "https";
Response.Redirect(uri.ToString());
}
}
Upvotes: 6
Reputation: 1
Because redirection goes in loop. its call same page again and again. like deadlock. Use this Code
if (Request.Url.Scheme.Contains("http"))
{
Response.Redirect(string.Format("https://{0}{1}", Request.Url.Authority, returnUrl), true);
}
Or
protected void Application_BeginRequest(Object source, EventArgs e)
{
if (!Context.Request.IsSecureConnection)
{
Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));
}
}
Upvotes: -2