简体   繁体   English

Asp.net 核心远程 IP 地址获取本地 ip (192.168.1.1)

[英]Asp.net Core Remote IP Address get local ip (192.168.1.1)

I am getting IP address by following code:我通过以下代码获取 IP 地址:

var remoteIpAddress = HttpContext?.Connection?.RemoteIpAddress?.ToString ();

This is working okay when I am running on IIS with accessing by IP address (public IP address of my ISP network).当我在 IIS 上运行并通过 IP 地址(我的 ISP 网络的公共 IP 地址)访问时,这可以正常工作。

I host on another server but mapping to domain name (cannot be accessed by IP due to multiple website hosting on IIS).我在另一台服务器上托管,但映射到域名(IP 无法访问,因为 IIS 上有多个网站托管)。

It is working fine just not getting the remote IP address of client acceessing.它工作正常,只是没有获得客户端访问的远程 IP 地址。

Also, I try the following code recommended by Microsoft but it is not working.另外,我尝试了 Microsoft 推荐的以下代码,但它不起作用。

  services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = 
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

Here is a solution to get client IP address in ASP.NET Core.这是在 ASP.NET 核心中获取客户端 IP 地址的解决方案。

Inject the HttpContextAccessor instance in the ConfigureServices method from the Startup.cs class.在 Startup.cs class 的 ConfigureServices 方法中注入 HttpContextAccessor 实例。 Now add this reference using Microsoft.AspNetCore.Http.现在使用 Microsoft.AspNetCore.Http 添加此引用。

public void ConfigureServices(IServiceCollection services)
    {
         services.AddControllersWithViews();
         services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    }

Declare a variable.声明一个变量。

private readonly IActionContextAccessor _accessor;

Update the HomeController to inject the IActionContextAccessor in the constructor.更新 HomeController 以在构造函数中注入 IActionContextAccessor。 try to inject the IActionContextAccessor into the controller's constructor with DI.尝试使用 DI 将 IActionContextAccessor 注入到控制器的构造函数中。

public HomeController(ILogger logger, IActionContextAccessor accessor)
{
    _logger = logger;
    _accessor = accessor;
}

Now at last step try to retrieve the IP address from the accessor variable.现在在最后一步尝试从访问器变量中检索 IP 地址。

public IActionResult Index()
{
  var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();
  return View();
}

If you don not want to use DI, you can always access the IP information directly in the controller as followed.如果您不想使用 DI,您可以随时在 controller 中直接访问 IP 信息,如下所示。

var ip = HttpContext.Connection.RemoteIpAddress.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM