Can I detect if SSL/https is enabled for an ASP.NET website from within the site's code?
I'm working on a CMS that can run either with or without https enabled on the webserver. I'd like to be able to detect whether https is enabled or not, so that I can act accordingly (for example, display some https-related o开发者_StackOverflow中文版ptions to the administrator, and redirect to https for administrator logins).
I'm not looking for Request.IsSecureConnection because that only tells me if the current request is via https. I want something that will tell me whether the current bindings for the site in IIS include a binding for https at the same domain as the current request is on. So, for example, even if the current request is for http://example.com/
and thus not secure, I want to know whether https://example.com/
would work so I can (for example) redirect the user to it if they log in as administrator.
I've had no luck looking for anything in System.Web.Configuration that will tell me about the bindings of the current site, though.
My current workaround is just to require the administrator to set an appSetting in web.config if https is enabled, but I'd prefer if I could make it automatic. Having to set the same thing twice - once in IIS and once in web.config - is confusing.
The simplest way is to make an https request to the site from the site and if it succeeds then you know https is supported. Cache this in a static variable so it's only called once per app invocation.
Depending on your IIS version you can use managemed .net code to do administrative tasks in IIS7. This is an example of querying a site for its bindings to see if https is enabled
http://msdn.microsoft.com/en-us/library/microsoft.web.administration.bindingcollection(v=VS.90).aspx
精彩评论