我有一段如下代码:
public static class RequestExtensions
{
public static string GetIpAddress(this HttpRequestBase request)
{
if (request.Headers["CF-CONNECTING-IP"] != null)
return request.Headers["CF-CONNECTING-IP"];
var ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
var addresses = ipAddress.Split(',');
if (addresses.Length != 0)
return addresses[0];
}
return request.UserHostAddress;
}
}
这应该可以帮助我找出通过cloudflare连接到我的网站的用户的真实IP地址...
问题是我现在不知道如何通过控制器调用此扩展方法:
public actionresult Index()
{
// How do I now call the GetIpAddress extension method ??
}
有人可以帮我吗?
答案 0 :(得分:2)
请求对象存在于操作范围内
public ActionResult Index()
{
// Here is how you now call the GetIpAddress extension method
var ipString = this.Request.GetIpAddress();
}
不要忘记导入扩展方法
using RequestExtensionsNamespance