天天看點

在ASP.NET Core 2.x中擷取用戶端IP位址

一、前言

大家也知道服務端請求時我們擷取的IP位址是包含在請求頭中,是以這也大大便利了IP的擷取。

在ASP.NET中,可以通過以下方式擷取用戶端的IP位址。

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]      

但這不适用于ASP.NET Core 2.0。我們需要一種不同的方法來檢索HTTP請求資訊。

當然這邊具體的可以看微軟官方給出的文檔:

在 ASP.NET Core 中通路 HttpContext

那麼接下來我們來配置一下吧

二、配置

1、介紹asp.net 下的擷取IP代碼:

在ASP.NET Core 2.x中擷取用戶端IP位址
在ASP.NET Core 2.x中擷取用戶端IP位址
public static string IPAddress
        {
            get
            {
                string result = String.Empty;
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理
                    if (result.IndexOf(".") == -1)    //沒有“.”肯定是非IPv4格式
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”,估計多個代理。取第一個不是内網的IP。
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];    //找到不是内網的位址
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 ,IsIPAddress判斷是否是IP的方法,
                            return result;
                        else
                            result = null;    //代理中的内容 非IP,取IP
                    }

                }

                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;

                return result;
            }
        }

        public static bool IsIPAddress(string str)
        {
            if (string.IsNullOrWhiteSpace(str) || str.Length < 7 || str.Length > 15)
                return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}{1}quot;";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);

            return regex.IsMatch(str);
        }
    }      

View Code

上面代碼直接放在項目中就可以用了。

2、asp.net core 2.x上配置

第一步:在控制器中定義變量

private IHttpContextAccessor _accessor;      

第二步: 控制器的構造函數進行注入

public ValuesController(IHttpContextAccessor accessor)
{
    _accessor = accessor;
}      

第三步:在action中 調用

_accessor.HttpContext.Connection.RemoteIpAddress.ToString()      

第四步:我們應該要在startup.cs中配置IHttpContextAccessor

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc();
     services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}      

第五步:可以運作測試一下:

在ASP.NET Core 2.x中擷取用戶端IP位址

發現已經擷取到IP位址啦。

注:在ASP.NET 2.1中,在startup.cs需要修改成以下的内容:

services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();      

RemoteIpAddress

是類型的

IPAddress

,不是

string

。它包含IPv4,IPv6和其他資訊,它不像經典的ASP.NET,它對我們更有用。 

asp.net core 交流群:787464275 歡迎加群交流

如果您認為這篇文章還不錯或者有所收獲,您可以點選右下角的【推薦】按鈕精神支援,因為這種支援是我繼續寫作,分享的最大動力!

作者:

LouieGuo http://www.cnblogs.com/stulzq

聲明:原創部落格請在轉載時保留原文連結或者在文章開頭加上本人部落格位址,如發現錯誤,歡迎批評指正。凡是轉載于本人的文章,不能設定打賞功能,如有特殊需求請與本人聯系!

微信公衆号:歡迎關注                                                 QQ技術交流群: 歡迎加群

在ASP.NET Core 2.x中擷取用戶端IP位址
在ASP.NET Core 2.x中擷取用戶端IP位址

繼續閱讀