Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何判断HttpClient是否通过HTTPS连接_C#_.net_Https_Httpclient - Fatal编程技术网

C# 如何判断HttpClient是否通过HTTPS连接

C# 如何判断HttpClient是否通过HTTPS连接,c#,.net,https,httpclient,C#,.net,Https,Httpclient,我正在使用HttpClient与API对话。如果启用,服务器将自动将http://请求重定向到https://。因此,为了保护用户的API密钥,我想创建一个到网站的测试连接,看看在通过API密钥发送之前我是否被重定向 HttpClient正确重定向,但我似乎找不到一个合适的方法来确定客户端是否使用HTTPS。我知道我可以测试response.RequestMessage.RequestUri中是否存在https://,但这似乎有点古怪 public void DetectTransportMet

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

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

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
            }
        }
    }
}

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

请参见以下扩展方法:

static class Extensions
{
    public static bool IsSecure(this HttpResponseMessage message)
    {
        rreturn message.RequestMessage.RequestUri.Scheme == "https";
    }
}
下面的控制台应用程序演示了它的工作原理。但是,要使其正常工作,HTTP服务器必须将连接升级到https(就像Facebook一样),并且
WebRequestHandler
AllowAutoRedirect
属性必须设置为
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.ToString().ToLower().StartsWith(“https://”)来代替
message.RequestUri.ToString().ToLower()。