如何在使用ASP.NET开发的Azure Web应用程序中获取客户端IP地址?

9

我开发了一个Web应用程序,它作为Web应用程序部署在Azure上。

我需要获取客户端的IP地址,以便我可以使用GeoIP API来获取客户端连接的国家。

那么这里是我的问题,当他们发送请求查看主页时,如何获取客户端的IP地址?我正在使用ASP.NET MVC。


Request.ServerVariables["REMOTE_ADDR"]不能用? - hardkoded
我尝试了 System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];但它返回 null,["HTTP_X_FORWARDED_FOR"] 也是如此。 - EidolonMK
你可以查看这个列表 https://dev59.com/d2w05IYBdhLWcg3w9mnd#6914521 - hardkoded
Request.UserHostAddress 是什么? - Alex Kudryashev
1个回答

9

尝试以下方法(在使用 ASP.NET Core 2.x 的 Azure Web 应用上进行了验证):

using Microsoft.AspNetCore.Http.Features;
using System.Net;

....

var connection = HttpContext.Features.Get<IHttpConnectionFeature>();
IPAddress clientIP = connection.RemoteIpAddress;

IPv4地址?我认为不是。 - Ahmer Ali Ahsan
这适用于 .NET Core 3.1。 - James Westgate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接