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


    随着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

  • 相关阅读:
    BZOJ 2055 80人环游世界 有上下界最小费用可行流
    BZOJ 2406 LuoguP4194 矩阵 有上下界可行流
    BZOJ4873 LuoguP3749 寿司餐厅
    51nod 1551 集合交易 最大权闭合子图
    BZOJ 1565 植物大战僵尸 最大权闭合子图+网络流
    [CodeForces]460C Present
    [BZOJ5072] 小A的树
    [TJOI2015]组合数学
    [HNOI2006]鬼谷子的钱袋
    [IOI2007]矿工配餐
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12304062.html
Copyright © 2020-2023  润新知