如何确定C#中是否为HTTPS

8 浏览
0 Comments

如何确定C#中是否为HTTPS

我应该如何确定并强制用户仅使用HTTPS查看我的网站?我知道可以通过IIS完成,但想知道如何通过编程完成。

admin 更改状态以发布 2023年5月20日
0
0 Comments

有点硬编码,但很直观!

if (!HttpContext.Current.Request.IsSecureConnection)
{
   Response.Redirect("https://www.foo.com/foo/");
}

0
0 Comments

你可以编写一个像这样的 HttpModule

/// 
/// Used to correct non-secure requests to secure ones.
/// If the website backend requires of SSL use, the whole requests 
/// should be secure.
/// 
public class SecurityModule : IHttpModule
{
    public void Dispose() { }
    public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(application_BeginRequest);
    }
    protected void application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = ((HttpApplication)(sender));
        HttpRequest request = application.Request;
        HttpResponse response = application.Response;
        // if the secure connection is required for backend and the current 
        // request doesn't use SSL, redirecting the request to be secure
        if ({use SSL} && !request.IsSecureConnection)
        {
            string absoluteUri = request.Url.AbsoluteUri;
            response.Redirect(absoluteUri.Replace("http://", "https://"), true);
        }
    }
}

其中 {use SSL} 是一个条件,用于决定是否使用 SSL。

编辑:当然,别忘了将模块定义添加到 web.config 中:


    
        
        
        ...
    

0