获取远程主机的IP地址 [英] Get the IP address of the remote host

查看:63
本文介绍了获取远程主机的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ASP.NET 中有一个 System.Web.HttpRequest 类,它包含 ServerVariables 属性,它可以为我们提供来自 REMOTE_ADDR 财产价值.

In ASP.NET there is a System.Web.HttpRequest class, which contains ServerVariables property which can provide us the IP address from REMOTE_ADDR property value.

但是,我找不到类似的方法从 ASP.NET Web API 获取远程主机的 IP 地址.

However, I could not find a similar way to get the IP address of the remote host from ASP.NET Web API.

如何获取发出请求的远程主机的 IP 地址?

How can I get the IP address of the remote host that is making the request?

推荐答案

这样做是可以的,但不是很容易发现——你需要使用传入请求中的属性包,而你需要访问的属性取决于您在 IIS(网络托管)或自托管下使用 Web API.下面的代码展示了如何做到这一点.

It's possible to do that, but not very discoverable - you need to use the property bag from the incoming request, and the property you need to access depends on whether you're using the Web API under IIS (webhosted) or self-hosted. The code below shows how this can be done.

private string GetClientIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }

    if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
        RemoteEndpointMessageProperty prop;
        prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
        return prop.Address;
    }

    return null;
}

这篇关于获取远程主机的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆