17

How would you read the following server variables in an ASP.NET Web API controller?

HTTP_HOST
SERVER_NAME
REMOTE_HOST / REMOTE_ADDR

I see a System.Net.Http.HttpRequestMessage Request defined, but I don't see a collection containing these variables.

I'm running a website on a single IP with multiple host headers and I need to determine which site they used to get there.

EDIT:

It ended up being something like this:

((System.Web.HttpContextWrapper) Request.Properties["MS_HttpContext"])
    .Request.ServerVariables["HTTP_HOST"]
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
Zachary Scott
  • 20,968
  • 35
  • 123
  • 205

2 Answers2

13

The information you are looking for is dependent on the host you are using and Web API is designed to be host independent. So.... the information you are looking for will be buried in the httpRequestMessage.Properties collection and it will be different depending on your host.

If you move to using the Owin adapter then you will get a standardized Owin environment object.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • Good suggestions. I can see `Request.Properties["MS_HttpContext"].Request.Url` along with UrlReferrer. Big question is whether it represents the host header of the site they visited. – Zachary Scott May 03 '13 at 03:08
  • I wonder if http://msdn.microsoft.com/en-us/library/system.net.http.headers.httprequestheaders.aspx is a consistent way to read this information regardless of hosted environment? – Zachary Scott May 05 '13 at 18:35
  • 5
    ((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.ServerVariables["HTTP_HOST"] – Zachary Scott May 05 '13 at 18:52
  • 1
    Dr. Zim, your comment deserves its own answer. I come back to this every once in a while and have to read the whole page before I find your comment. – zacharydl Oct 31 '14 at 17:53
1

I was able to all that information from the RequestUri within Request

  Request.RequestUri.Scheme + Uri.SchemeDelimiter + 
  Request.RequestUri.Host + (Request.RequestUri.IsDefaultPort ? string.Empty : (string.Concat(":", Request.RequestUri.Port)))
TombMedia
  • 1,962
  • 2
  • 22
  • 27