获取远程计算机动态ip,c# - 获取远程主机的IP地址
此解決方案還涵蓋使用Owin自托管的Web API。 部分來自這里。
您可以在dynamic中創(chuàng)建一個私有方法,無論您如何托管Web API,它都將返回遠程IP地址:
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage =
"System.ServiceModel.Channels.RemoteEndpointMessageProperty";
private const string OwinContext = "MS_OwinContext";
private string GetClientIp(HttpRequestMessage request)
{
// Web-hosting
if (request.Properties.ContainsKey(HttpContext ))
{
HttpContextWrapper ctx =
(HttpContextWrapper)request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
// Self-hosting
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
RemoteEndpointMessageProperty remoteEndpoint =
(RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
// Self-hosting using Owin
if (request.Properties.ContainsKey(OwinContext))
{
OwinContext owinContext = (OwinContext)request.Properties[OwinContext];
if (owinContext != null)
{
return owinContext.Request.RemoteIpAddress;
}
}
return null;
}
所需參考:
dynamic - System.Web.dll
dynamic - System.ServiceModel.dll
dynamic - Microsoft.Owin.dll(如果您使用Owin包,您將擁有它)
這個解決方案的一個小問題是,當你在運行時實際只使用其中一個時,你必須為所有3個案例加載庫。 正如這里建議的那樣,這可以通過使用dynamic變量來克服。 您也可以將GetClientIpAddress方法寫為HttpRequestMethod的擴展。
using System.Net.Http;
public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage =
"System.ServiceModel.Channels.RemoteEndpointMessageProperty";
private const string OwinContext = "MS_OwinContext";
public static string GetClientIpAddress(this HttpRequestMessage request)
{
// Web-hosting. Needs reference to System.Web.dll
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
// Self-hosting. Needs reference to System.ServiceModel.dll.
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
// Self-hosting using Owin. Needs reference to Microsoft.Owin.dll.
if (request.Properties.ContainsKey(OwinContext))
{
dynamic owinContext = request.Properties[OwinContext];
if (owinContext != null)
{
return owinContext.Request.RemoteIpAddress;
}
}
return null;
}
}
現(xiàn)在您可以像這樣使用它:
public class TestController : ApiController
{
[HttpPost]
[ActionName("TestRemoteIp")]
public string TestRemoteIp()
{
return Request.GetClientIpAddress();
}
}
總結(jié)
以上是生活随笔為你收集整理的获取远程计算机动态ip,c# - 获取远程主机的IP地址的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机丢失qt5sql.ll,电脑中提示
- 下一篇: 软件测试缺陷发生方法,软件测试缺陷分析方