簡體   English   中英

如何在ASP.NET CORE中自動獲取客戶端的IP

[英]How to get the client's IP automatically in ASP.NET CORE

我想在沒有用戶自動提交來自 URL 本身的請求的情況下找到用戶的 IP。 When I do this locally, it returns the correct IP address, but when I publish the web service on the server, this IP becomes the server IP, what should I do?

例如,我在地址https://test.com/api/GetAddress有一個服務,我使用以下代碼在PostMan中調用此服務,它正確返回用戶的 ZA12A3079E14CED46E61AZ9BA52B8A地址https://sitetest.com/Dashboard/GetHome被調用,服務器地址被返回,用戶地址沒有給我。

Note that I want to get this IP through the URL itself, because if I put this in the Request and it is received through the developer, it can give any IP to the Api.

我使用了兩種類型的代碼,但仍然相同:

public static string GetClientIp()
    {
        try
        {
            string strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList
                .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

            return ipAddress?.ToString();
        }
        catch (Exception ex)
        {
            return "0.0.0.0";
        }
        
        //return HttpContext.Current.Connection.RemoteIpAddress?.ToString() ?? "0.0.0.0";
    }

在 controller 中獲取客戶端 ip 地址,使用:

var address = Request.HttpContext.Connection.RemoteIpAddress;

如果您使用的是反向代理,那么您必須使用 Forwarded Headers 中間件。 例子:

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

這是因為代理將請求轉發到您的應用程序,因此 RemoteIpAdress 具有運行代理的機器的 ip 地址。 大多數代理通常將 X-Forwarded-For header 設置為原始 ip 地址。 此中間件讀取 X-Forwarded-For header 並正確設置 RemoteIpAdress。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM