如何获取远程IP地址

如何获取远程IP地址

本文介绍了ASP.NET核心:如何获取远程IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试获取远程(客户端)IP地址:

I try to get remote (client) IP addres:

var ip = httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress

但它仅适用于本地请求(它将返回 :: 1 value)

But it works only for local requests (it will return ::1 value)

当我从远程机器加载页面时,该值为null。我调查了在这种情况下 Features 集合中没有 IHttpConnectionFeature

When I load page from remote machine the value is null. I investigated there is no IHttpConnectionFeature in the Features collection in this case.

为什么?以及如何正确获取远程IP地址?

Why? And how to get remote ip address correctly?

推荐答案

我知道这篇文章很老但我来这里寻找同样的问题和finnaly我这样做了:

I know that this post is old but I came here looking for the same question and finnaly I did this:

在project.json上添加依赖项:

On project.json add dependency:

"Microsoft.AspNetCore.HttpOverrides": "1.0.0"

在Startup.cs上,配置方法添加:

On Startup.cs, in the Configure method add:

  app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor |
            ForwardedHeaders.XForwardedProto
        });

当然还有:

using Microsoft.AspNetCore.HttpOverrides;

然后,我得到了这样的ip:

Then, I got the ip like this:

Request.HttpContext.Connection.RemoteIpAddress

在我的例如,在VS中进行调试我总是得到IpV6 localhost,但是当部署在IIS上时,我总是得到远程IP。

In my case, when debugging in VS I got always IpV6 localhost, but when deployed on an IIS I got always the remote IP.

一些有用的链接:

:: 1可能是因为:

The ::1 may be because:

这篇关于ASP.NET核心:如何获取远程IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 12:28