ASP.NET Web API: How do you read server variables

2020-02-05 06:19发布

问题:

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"]

回答1:

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.



回答2:

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)))