访客IP地址不显示

visitors IP address doesnt show

我在获取访问者 ip 地址时遇到问题 我正在使用 asp net mvc 我使用以下代码来保存访问者的 IP 地址,但不幸的是,它在我的本地网络上不起作用,许多人从 LAN 访问了我的页面,但没有捕获到任何一个,我有一个包含很多页面的网站,如果用户访问了另一个页面也它根本不会捕获的问题,因为我在主页索引中有代码 请让我知道我的代码有什么问题以及我必须将代码放置在项目中的什么位置,以便在用户单击 link 而不是主页时它会捕获任何页面的访问者 这是我的代码 家庭控制器

public ActionResult Index()
        {
            string currip = string.Empty;
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                currip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0)
            {
                currip = System.Web.HttpContext.Current.Request.UserHostAddress;

            }
         //   string currip = HttpContext.Request.UserHostAddress.ToString(); // tried this didnt work it gave me single ip for all visitors 
             //   vs.Ip = currip;
                vs.Ip = HttpContext.Request.UserHostAddress.ToString();
                vs.lastaccess = DateTime.Now;
                vs.visits += 1;
                _db.SaveChanges();           
           
           return view();
}

更新 使用时 currip = System.Web.HttpContext.Current.Request.UserHostAddress; 对于post方法添加登录信息ip出现但是对于访问它没有出现因为它是get方法 有什么关系吗?

public static string getIPAddress(HttpRequestBase request)
    {
        string ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ipAddress))
        {
            ipAddress = request.ServerVariables["REMOTE_ADDR"];
        }

        return ipAddress;
    }

更新

您可以使用访问属性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class VisitAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var descriptor = filterContext.ActionDescriptor;
        var controller = descriptor.ControllerDescriptor.ControllerName;
        var action = descriptor.ActionName;
        var user = filterContext.HttpContext.User.Identity.Name;

        // your code here 
     }
}

然后你可以像这样调用你的控制器或动作:

[Visit]
public class YourController : Controller
{

}

Wowo Ot 答案的补充,我试过但没有用,答案在逻辑上是正确的,但我的代码有问题 旧代码

vs.visits += 1;
_db.SaveChanges();   

我不得不编辑我的代码 至

vs.visits += 1;
_db.visit.add(vs); // here was the missing code 
_db.SaveChanges();