📜  在 Asp.Net Core 核心中如何获取网站的 IP 地址? - C# (1)

📅  最后修改于: 2023-12-03 14:50:51.397000             🧑  作者: Mango

在 Asp.Net Core 核心中如何获取网站的 IP 地址? - C#

简介

在 Asp.Net Core 核心中,获取网站的 IP 地址是一个非常基础的操作。它可以用于构建更复杂的应用程序,例如记录日志、限制访问等。本文将介绍如何在 Asp.Net Core 中获取网站的 IP 地址。

获取 IP 地址

获取 IP 地址的方法基本相同,无论是 Asp.Net 还是 Asp.Net Core。唯一的区别是 Asp.Net Core 使用了不同的命名空间。

在 Asp.Net Core 中,获取 IP 地址的最简单方式是使用 HttpContext 对象。可以通过 HttpContext.Connection.RemoteIpAddress 属性来获取当前请求的远程 IP 地址。代码示例如下:

using Microsoft.AspNetCore.Http;
// ...
public IActionResult Index()
{
    var ipAddress = HttpContext?.Connection?.RemoteIpAddress?.ToString();
    return View();
}

上述代码中,RemoteIpAddress 属性返回一个 IPAddress 对象。为了获取该对象的字符串表示形式,必须将其 ToString()。

处理 IPv4 和 IPv6

需要注意的是,IPAddress 对象可能包含 IPv4 或 IPv6 地址。有时,您可能需要仅仅采用 IPv4 或者 IPv6 地址。这可以通过使用 IPAddressExtensions 中的方法来实现。以下是示例代码:

using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Http.Features;
// ...
public IActionResult Index()
{
    var remoteIpAddress = HttpContext?.Connection?.RemoteIpAddress;
    if (remoteIpAddress != null)
    {
        // 如果是 IPv4,则将其转换为 IPv4 否则返回 IPv6 地址
        if (remoteIpAddress.IsIPv4MappedToIPv6)
        {
            remoteIpAddress = remoteIpAddress.MapToIPv4();
        }
        var ipAddress = remoteIpAddress.ToString();
    }
    return View();
}
结论

无论是在 Asp.Net 还是 Asp.Net Core,获取当前请求的 IP 地址都是一个相当基础的操作。通过 HttpContext.Connection.RemoteIpAddress 属性可以获得远程 IP 地址。为了获取字符串表示形式,必须将 IPAddress 对象 ToString()。注意,在某些情况下,IPAddress 对象可能包含 IPv4 或 IPv6 地址。如果需要,可以通过 IPAddressExtensions 中的方法处理它们。