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()。