how to redirect from http to https in asp.net C# and make it as default version for the website

大憨熊 提交于 2019-12-05 08:47:05

Are you looking for something like this:-

if (!Request.IsLocal && !Request.IsSecureConnection)
{
    string sUrl = Request.Url.ToString().Replace("http:", "https:");
    Response.Redirect(sUrl);
}

Also check this related forum.

From the above link:-

You can install URL Rewrite Module, create a redirect rule and put it to your web.config file

<rule name="http to https" stopProcessing="true">
     <match url=".*" />
     <conditions>
     <add input="{HTTPS}" pattern="off" />
     </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}/{R:0}" />
 </rule>

A far cleaner/easier way of doing it than mentioned above is to use the RequireHttpsAttribute class within the System.Web.Mvc package.

Simply register the attribute by adding it to the FilterConfig.RegisterGlobalFilters() method that's invoked inside of Global.asax.cs like so:

FilterConfig.cs

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new RequireHttpsAttribute());
    }
}

This will register the RequireHttps attribute across all controller classes, forcing it to redirect to HTTPS if it isn't already doing so.

Note: This is only applicable to ASP.NET MVC and not WebAPI.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!