gpt4 book ai didi

c# - Asp.NET MVC REST API : How to get Client Host Name

转载 作者:太空狗 更新时间:2023-10-29 23:22:13 31 4
gpt4 key购买 nike

我正在 ASP.NET MVC3 中开发 REST API 应用程序。我正在尝试让客户端客户端 HOST 名称生效,但无法成功。我在多个应用程序中使用此 API,因此我想记录域名。

Link 1

 HttpContext.Current.Request.UserHostAddress;
System.Web.HttpContext.Current.Request.UserHostName;
System.Web.HttpContext.Current.Request.UserHostAddress;

Link 2

private string GetClientIp(HttpRequestMessage request)
{
if (request.Properties.ContainsKey("MS_HttpContext"))
{
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
}
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
{
RemoteEndpointMessageProperty prop;
prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
return prop.Address;
}
else
{
return null;
}
}

所有这些选项都提供 IP 地址,但我想获取主机名

API Controller www.myapi.com

public class TESTController : ApiController
{
public TESTController()
{
}

[HttpGet]
public object Add(string data = "")
{
try
{
string result = "0";

if (!string.IsNullOrEmpty(data))
{
//should be www.myapiconsume.com
var host = System.Web.HttpContext.Current.Request.UserHostName;
var ip = System.Web.HttpContext.Current.Request.UserHostAddress;
}

return new { response = result };
}
catch (Exception ex)
{
throw ex;
}

}
}

从不同域调用 API 操作 www.myapiconsume.com

 public class HomeController : Controller
{
public ActionResult Index()
{
var url = "http://myapi.com/api/test/add?data={0}";
url = string.Format(url, "{ data}");
WebClient client = new WebClient();
var result = client.DownloadString(url);
return Content(result);
}

}

我怎样才能得到这个?

最佳答案

您可以使用 Dns.GetHostEntry反向查找的方法。

public static string ReverseLookup(string ip)
{
if (String.IsNullOrWhiteSpace(ip))
return ip;

try
{
IPHostEntry host = Dns.GetHostEntry(ip);

return host != null ? host.HostName : ip;
}
catch (SocketException)
{
return ip;
}
}

关于c# - Asp.NET MVC REST API : How to get Client Host Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26487863/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com