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

2020-02-05 06:32发布

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

2条回答
手持菜刀,她持情操
2楼-- · 2020-02-05 07:21

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)))
查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-05 07:26

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.

查看更多
登录 后发表回答