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

人走茶凉 提交于 2019-12-22 05:29:25

问题


how to redirect from http to https in asp.net c# i have installed https certificate now i want to make https as default version for my website iam using windows server 2008 R2 asp.net C# 4.0


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/19474437/how-to-redirect-from-http-to-https-in-asp-net-c-sharp-and-make-it-as-default-ver

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