I am trying to redirect to https
I used the code below in Global.asax
protected void Application_BeginRequest()
{
if (!Context.Request.IsSecureConnection)
Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
}
but my problem is that I have to add www in front of link, ie mywesite.se and after redirecting to https its like https://mywebsite.se but I want it like https://www.mywebsite.se
Use UriBuilder :
var url = Context.Request.Url;
var builder = new UriBuilder(url);
builder.Scheme = "https";
if (!url.Host.StartsWith("www"))
builder.Host = "www." + url.Host;
Response.Redirect(builder.Uri);
Disclaimer: I didn't test this code.
You can add rewrite rule in web.config
<rewrite>
<rules>
<clear />
<rule name="Redirect non-www OR non-https to https://www">
<match url=".*" />
<conditions logicalGrouping="MatchAny">
<add input="{HTTP_HOST}" pattern="^mywebsite.se$" />
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://www.mywebsite.se/{R:0}" redirectType="Permanent"/>
</rule>
</rules>
</rewrite>
Here you go (write into web.config file)
void Application_BeginRequest(object sender, EventArgs e)
{
string lowerCaseURL = HttpContext.Current.Request.Url.ToString().ToLower();
if (lowerCaseURL.IndexOf("http://dotnetfunda.com") >= 0) // >= because http starts from the 0 position : )
{
lowerCaseURL = lowerCaseURL.Replace("http://dotnetfunda.com", "https://www.dotnetfunda.com");
HttpContext.Current.Response.StatusCode = 301;
HttpContext.Current.Response.AddHeader("location", lowerCaseURL);
HttpContext.Current.Response.End();
}
}
Replace dotnetfunda.com to yourwebsitedomainname.se
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.