Asp.net Redirecting from Https to Http

前端 未结 5 476
长情又很酷
长情又很酷 2020-12-21 15:45

I am trying to redirect from secure (https) to http when user login. It redirects fine but for some reason its keeping the https.

 Response.Redirect(Redirect         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-21 16:25

    Here's my 2 cents...

    Make a simple attribute class like this:

    public class ForceSSL : System.Attribute{
    
    public bool Enabled;
    
    public ForceSSL(bool _enabled)
        Enabled = _enabled; }
    

    Next, create a base class for your page(s) to inherit from. Inside the base class override the OnPreInit event as such (building from the example above @ Druid):

        protected override void OnPreInit(EventArgs e)
    {
        if (!Request.IsSecureConnection)
        {
            var _sslAttr = this.GetType().GetCustomAttributes(true).Where(at => (at as ForceSSL) != null).FirstOrDefault();
            if (_sslAttr != null)
            {
                if ((_sslAttr as ForceSSL).Enabled)
                {
                    var ub = new UriBuilder(Request.Url);
                    ub.Scheme = Uri.UriSchemeHttps;
                    ub.Port = -1;
                    Response.Redirect(ub.Uri.ToString(), true);
                    return;
                }
            }
        }
        base.OnPreInit(e);
    }
    

    Now just make your pages inherit from your base class and place the attribute [ForceSSL(true)] at the top of each page that you want to access via SSL.

提交回复
热议问题