Posted By

jasonseney on 03/18/11


Tagged

aspnet


Versions (?)

Last Edited at 03/18/11 07:33am

Viewed 3 times

Get the Host Name in ASP.NET C#


/ Published in: C#

Will return the host name that the site is running on. Example:

`http://mysite.com` or `http://myspecialsite.com:102`

  1. public static string ServerHostName()
  2. {
  3. string port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
  4. if (port == null || port == "80" || port == "443")
  5. {
  6. port = "";
  7. }
  8. else
  9. {
  10. port = ":" + port;
  11. }
  12.  
  13. string protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
  14. if (protocol == null || protocol == "0")
  15. {
  16. protocol = "http://";
  17. }
  18. else
  19. {
  20. protocol = "https://";
  21. }
  22.  
  23. return protocol + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port;
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.