C#如何确定HTTPS [英] C# How to determine if HTTPS

查看:750
本文介绍了C#如何确定HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确定,并强制用户使用HTTPS只浏览到我的网站?我知道它可以通过IIS来完成,但是要懂得它的编程方式完成的。

How do I determine and force users to view my website using HTTPS only? I know it can be done through IIS, but want to know how its done programmatically.

推荐答案

您可以写一个的HttpModule 是这样的:

You can write an HttpModule like this:

/// <summary>
/// Used to correct non-secure requests to secure ones.
/// If the website backend requires of SSL use, the whole requests 
/// should be secure.
/// </summary>
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);
        }
    }
}



其中, {使用SSL} 是一些条件是否使用SSL与否

Where {use SSL} is a some condition whether to use SSL or not.

修改:与,的当然,不要忘了模块定义添加到的web.config

EDIT: and, of course, don't forget to add a module definition to a web.config:

<system.web>
    <httpModules>
        <!--Used to redirect all the unsecure connections to the secure ones if necessary-->
        <add name="Security" type="{YourNamespace}.Handlers.SecurityModule, {YourAssembly}" />
        ...
    </httpModules>
</system.web>

这篇关于C#如何确定HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆