44

I have a web application hosted on multiple servers some of which are on https. How can I check from code behind if a page is currently in http or https?

Drahcir
  • 12,311
  • 19
  • 63
  • 76

7 Answers7

86

You can refer to the Request.IsSecureConnection property on the HttpRequest class. For a full reference outside a page, user control or alike, use HttpContext.Current.Request.IsSecureConnection.

Troels Thomsen
  • 11,361
  • 4
  • 28
  • 29
  • 8
    Beware- IsSecureConnection can give false negatives. http://stackoverflow.com/questions/998397/why-does-request-issecureconnection-return-false-when-true-is-expected – Jude Allred Mar 28 '11 at 21:13
  • 2
    Answer is little old, so now, for me it was a bit changed with owin. I got the value by "System.Web.HttpContext.Current.GetOwinContext().Request.IsSecure". May be this comes handy for some one later. :) – MGR May 11 '16 at 11:11
29
Page.Request.Url.Scheme

works as well. It returns http, https, etc.

Ref: http://msdn.microsoft.com/en-us/library/system.uri.scheme.aspx

wisbucky
  • 33,218
  • 10
  • 150
  • 101
Ankur-m
  • 528
  • 6
  • 14
8

Use - HttpContext.Current.Request.IsSecureConnection

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
Rashack
  • 4,667
  • 2
  • 26
  • 35
8

Update for Aspnet Core 2.0, now, you should use Request.IsHttps inside your controllers.

  • As of NET Core 2.2 you can use ```Request.Scheme``` which should return either ```https``` or ```http```. Either work fine on Windows servers although on Ubuntu ```IsHttps``` and ```Request.Scheme``` both say the request is not secure for me so not sure if this is a bug or something configured wrongly. – Robin Wilson Jan 04 '19 at 23:54
4

Alternatively:

Request.ServerVariables["SERVER_PROTOCOL"];
Mr. Smith
  • 5,489
  • 11
  • 44
  • 60
  • 1
    This returns `HTTP/1.1` for me on both http and https while `Request.IsSecureConnection` returns as expected. – atheaos Jan 27 '16 at 15:27
2

In .net core I use:

Context.Request.Scheme == Uri.UriSchemeHttps
Shadi Alnamrouti
  • 11,796
  • 4
  • 56
  • 54
1

Try this,

aCookie.Secure = HttpContext.Current.Request.IsSecureConnection
Andro Selva
  • 53,910
  • 52
  • 193
  • 240