随着ASP.NET的发展,有不同的方式从请求中访问客户端IP地址。WebForms和MVC Web应用程序只是访问当前HTTP上下文的请求。
var ip = HttpContext.Current.Request.UserHostAddress;
但是,这在ASP.NET Core 2.0及更高版本中不起作用。您必须从ConfigureServices方法中的Startup.cs类中注入HttpContextAccessor实例。
public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddMvc(); }
现在我们需要在我们的控制器构造函数中使用它并将其分配给控制器级别声明的变量,这样,它可以从控制器中的所有Actions访问,注意我们这里还使用了NetworkInterface.GetAllNetworkInterfaces()方法来获取服务器上所有网卡的IP地址:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using System.Net; using System.Net.NetworkInformation; using System.Linq; using System.Net.Sockets; namespace AspNetCoreIP.Controllers { public class HomeController : Controller { protected readonly IHttpContextAccessor httpContextAccessor; public HomeController(IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor; } public IActionResult Index() { //获取客户端的IP地址 string clientIpAddress = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); this.ViewData["ClientIpAddress"] = clientIpAddress; //获取服务器上所有网卡的IP地址 NetworkInterface[] networks = NetworkInterface.GetAllNetworkInterfaces(); string serverIpAddresses = string.Empty; foreach (var network in networks) { var ipAddress = network.GetIPProperties().UnicastAddresses.Where(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address)).FirstOrDefault()?.Address.ToString(); serverIpAddresses += network.Name + ":" + ipAddress + "|"; } this.ViewData["ServerIpAddresses"] = serverIpAddresses; return View(); } } }
11