【问题标题】:How can I tell if HttpClient is connecting via HTTPS如何判断 HttpClient 是否通过 HTTPS 连接
【发布时间】:2015-04-10 08:39:37
【问题描述】:

我正在使用HttpClient 与 API 对话。如果启用,服务器将自动将http:// 请求重定向到https://。因此,为了保护用户的 API 密钥,我想创建一个到网站的测试连接,以查看在通过 API 密钥发送之前是否被重定向。

HttpClient 正确重定向,但我似乎找不到合适的方法来确定客户端是否使用 HTTPS。我知道我可以测试https:// 是否存在于response.RequestMessage.RequestUri 中,但这似乎有点不稳定

public void DetectTransportMethod()
{
    using (HttpClient client = new HttpClient())
    {
        client.Timeout = TimeSpan.FromSeconds(20);

        using (HttpResponseMessage response = client.GetAsync(this.HttpHostname).Result)
        {
            using (HttpContent content = response.Content)
            {
                // check if the method is HTTPS or not
            }
        }
    }
}

【问题讨论】:

    标签: c# .net https httpclient


    【解决方案1】:

    HttpClient (MSDN) 和 HttpResponseMessage (MSDN) 的文档不包含任何可用于确定是否已通过 https 发出请求的方法。尽管检查 HttpResponseMessage 的 URI 确实听起来很不稳定,但恐怕它是最简单和最易读的选项。将其实现为HttpResponseMessage 的扩展方法可能是最易读的。为确保您正在使用的 HttpClient 可以被重定向,请确保传递到 HttpClientWebRequestHandler (MSDN) 将 AllowAutoRedirect (MSDN) 属性设置为 true。

    见以下扩展方法:

    static class Extensions
    {
        public static bool IsSecure(this HttpResponseMessage message)
        {
            rreturn message.RequestMessage.RequestUri.Scheme == "https";
        }
    }
    

    下面的控制台应用程序演示了它的工作原理。但是,要使其正常工作,HTTP 服务器必须将连接升级到 https(就像 Facebook 所做的那样),并且必须将 WebRequestHandlerAllowAutoRedirect 属性设置为 true

    static void Main(string[] args)
    {
         using (var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = true}))
         {
             client.Timeout = TimeSpan.FromSeconds(20);
    
             using (var response = client.GetAsync("http://www.geenstijl.nl").Result)
             {
                 Console.WriteLine(response.IsSecure());
             }
    
             using (var response = client.GetAsync("http://www.facebook.com").Result)
             {
                 Console.WriteLine(response.IsSecure());
             }
         }
    
         Console.ReadLine();
    }
    

    【讨论】:

    • 你可以使用message.RequestMessage.RequestUri.Scheme == "https"而不是message.RequestMessage.RequestUri.ToString().ToLower().StartsWith("https://")
    猜你喜欢
    • 2011-10-23
    • 2012-04-18
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多