1、在ConfigureServices注入IHttpContextAccessor
// ASP.NET Core 2.1的注入方式 //services.AddHttpContextAccessor(); //services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>(); // 注入 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
2、控制器里获取IP
private readonly IHttpContextAccessor _accessor; public HomeController(IHttpContextAccessor accessor) { _accessor = accessor; } public IActionResult Index() { // 获取客户端的IP string ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(); return View(); }
3、页面里获取IP
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor @{ ViewData["Title"] = "Privacy Policy"; } <h1>@ViewData["Title"]</h1> <p>客户端IP:@HttpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString().</p>
原文地址:https://www.cnblogs.com/zhouxiaoyun/p/10765509.html
时间: 2024-11-06 12:13:04