.NET6 ASP.NET CORE MVC 获取客户端IP

在Program.cs中增加一行:

//获取IP使用
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

注入:

 public HomeController(ILogger<HomeController> logger, IManager user, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _user = user;
            _httpContextAccessor = httpContextAccessor;
        }

使用

复制代码
 public IActionResult Index()
        {
           //注入
            var ip = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            ViewBag.myip = "ip:" + ip;

            //直接实例化HttpContextAccessor
            IHttpContextAccessor ih = new HttpContextAccessor();
            string ip2 = ih.HttpContext.Connection.RemoteIpAddress.ToString();
            ViewBag.myip = "ip2:" + ip2;

            //使用ControllerBase的HttpContext
            var ip3 = HttpContext.Connection.RemoteIpAddress.ToString();
            ViewBag.myip = "ip3:" + ip3;

            return View();
        }
复制代码

 

posted @   流氓大菠萝  阅读(1027)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
点击右上角即可分享
微信分享提示