在ASP.NET Core中获取客户端和服务器端的IP地址

随着ASP.NET的发展,有不同的方式从请求中访问客户端IP地址。WebForms和MVC Web应用程序只是访问当前HTTP上下文的请求。

var ip = HttpContext.Current.Request.UserHostAddress;

或者只是直接引用当前的Request

var ip = Request.UserHostAddress;

 

但是,这在ASP.NET Core 2.0及更高版本中不起作用。您必须从ConfigureServices方法中的Startup.cs类中注入HttpContextAccessor实例。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton();
    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();
        }
    }
}

建立MVC视图Index.cshtml,来显示客户端和服务器端的IP地址:

@{
    Layout = null;
}

DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Indextitle>
head>
<body>
    <div>
        客户端IP地址:@this.ViewData["ClientIpAddress"].ToString()
    div>
    <div>
        服务器所有网卡的IP地址:@this.ViewData["ServerIpAddresses"].ToString()
    div>
body>
html>

 

为什么有时候httpContextAccessor.HttpContext.Connection.RemoteIpAddress获取到的客户端IP地址为空,请参见下文链接:

How do I get client IP address in ASP.NET CORE?

 

原文链接

 

你可能感兴趣的:(在ASP.NET Core中获取客户端和服务器端的IP地址)