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
  • 11,771
  • 18
  • 62
  • 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
  • 10,925
  • 4
  • 27
  • 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
28
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
  • 27,562
  • 9
  • 122
  • 88
Ankur-m
  • 508
  • 6
  • 13
8

Use - HttpContext.Current.Request.IsSecureConnection

Cᴏʀʏ
  • 101,556
  • 20
  • 162
  • 188
Rashack
  • 4,648
  • 2
  • 25
  • 35
5

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,321
  • 10
  • 41
  • 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
1

In .net core I use:

Context.Request.Scheme == Uri.UriSchemeHttps
Shadi Namrouti
  • 9,714
  • 1
  • 47
  • 51
1

Try this,

aCookie.Secure = HttpContext.Current.Request.IsSecureConnection
Andro Selva
  • 53,136
  • 52
  • 190
  • 238