2013-05-02 166 views
13

如何阅读ASP.NET Web API控制器中的以下服务器变量?ASP.NET Web API:如何读取Web API控制器中的服务器变量?

HTTP_HOST 
SERVER_NAME 
REMOTE_HOST/REMOTE_ADDR 

我看到一个System.Net.Http.HttpRequestMessage请求定义,但我看不出含有这些变量的集合。

我正在一个IP上运行一个网站与多个主机标题,我需要确定他们用来到达那里的网站。

编辑:

它结束了是这样的:

((System.Web.HttpContextWrapper) Request.Properties["MS_HttpContext"]) 
    .Request.ServerVariables["HTTP_HOST"] 
+2

这会是你在找什么:http://stackoverflow.com/questions/9565889/get-the-ip-远程主机的地址 – 2013-05-02 06:53:45

+1

@MajorByte这非常类似。 – 2013-05-05 18:58:57

回答

11

你正在寻找的信息取决于你正在使用的主机上,并Web API被设计为独立于主机。所以......你正在寻找的信息将被隐藏在httpRequestMessage.Properties集合中,这取决于你的主机。

如果您转向使用Owin适配器,那么您将获得标准化的Owin环境对象。

+0

好的建议。我可以看到Request.Properties [“MS_HttpContext”],Request.Url和UrlReferrer。很大的问题是它是否表示他们访问的网站的主机标题。 – 2013-05-03 03:08:28

+0

我不知道是否http://msdn.microsoft.com/en-us/library/system.net.http.headers.httprequestheaders.aspx是一个一致的方式来阅读这些信息,无论托管环境? – 2013-05-05 18:35:51

+4

((System.Web.HttpContextWrapper)Request.Properties [“MS_HttpContext”])。Request.ServerVariables [“HTTP_HOST”] – 2013-05-05 18:52:48

-11

就这样

using System; 
using System.Web.Mvc; 

public class MyController : Controller 
{ 
    public ActionResult Index() 
    { 
     var httpHost = Request.ServerVariables["HTTP_HOST"]; 
     // etc 
    } 
} 
+1

'System.Net.Http.HttpRequestMessage'没有包含'ServerVariables'的定义,也没有找到接受类型'System.Net.Http.HttpRequestMessage'的第一个参数的扩展方法'ServerVariables'(你是否缺少一个using指令或程序集引用?) – 2013-05-02 05:46:00

+0

你能发布你的源代码吗?另外,检查你有'使用系统;使用System.Web.Mvc;'在文件顶部的 – 2013-05-02 05:55:41

+0

系统; System.Collections.Generic; System.Linq; System.Net; System.Net.Http; System.Web.Http;因为它是一个MVC API,所以它似乎没有使用正常的请求对象 – 2013-05-02 06:00:52

2

我能够从RequestUri所有信息请求中

Request.RequestUri.Scheme + Uri.SchemeDelimiter + 
    Request.RequestUri.Host + (Request.RequestUri.IsDefaultPort ? string.Empty : (string.Concat(":", Request.RequestUri.Port)))