如何在 ASP.NET CORE 中获取客户端 IP ?
生活随笔
收集整理的這篇文章主要介紹了
如何在 ASP.NET CORE 中获取客户端 IP ?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
咨詢區(qū)
eadam:
在 ASP.NET 中我可以用 Request.ServerVariables["REMOTE_ADDR"] 來獲取客戶端IP地址,請問在 ASP.NET Core 中我該如何實現(xiàn)呢?
回答區(qū)
CodingYourLife
如果你用的是 .NET 5,可以用內(nèi)部提供的擴展方法來實現(xiàn)獲取客戶端IP,參考代碼如下:
public?static?class?HttpContextExtensions {//https://gist.github.com/jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36public?static?IPAddress?GetRemoteIPAddress(this?HttpContext?context,?bool?allowForwarded?=?true){if?(allowForwarded){string?header?=?(context.Request.Headers["CF-Connecting-IP"].FirstOrDefault()????context.Request.Headers["X-Forwarded-For"].FirstOrDefault());if?(IPAddress.TryParse(header,?out?IPAddress?ip)){return?ip;}}return?context.Connection.RemoteIpAddress;} }然后像下面這樣調(diào)用。
var?ipFromExtensionMethod?=?HttpContext.GetRemoteIPAddress().ToString();crokusek:
在 ASP.NET Core 的世界里,一般都會在 Kestrel 前加上 IIS 或 Nginx 做負載均衡,在這種場景下獲取客戶端IP需要做一些額外處理,那就是在 Http Header 頭上增加 X-Forwarded-For 標記,其實不管有沒有負載均衡,建議都加上,參考代碼如下:
public?string?GetRequestIP(bool?tryUseXForwardHeader?=?true) {string?ip?=?null;//?todo?support?new?"Forwarded"?header?(2014)?https://en.wikipedia.org/wiki/X-Forwarded-For//?X-Forwarded-For?(csv?list):??Using?the?First?entry?in?the?list?seems?to?work//?for?99%?of?cases?however?it?has?been?suggested?that?a?better?(although?tedious)//?approach?might?be?to?read?each?IP?from?right?to?left?and?use?the?first?public?IP.//?http://stackoverflow.com/a/43554000/538763//if?(tryUseXForwardHeader)ip?=?GetHeaderValueAs<string>("X-Forwarded-For").SplitCsv().FirstOrDefault();//?RemoteIpAddress?is?always?null?in?DNX?RC1?Update1?(bug).if?(ip.IsNullOrWhitespace()?&&?_httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?!=?null)ip?=?_httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();if?(ip.IsNullOrWhitespace())ip?=?GetHeaderValueAs<string>("REMOTE_ADDR");//?_httpContextAccessor.HttpContext?.Request?.Host?this?is?the?local?host.if?(ip.IsNullOrWhitespace())throw?new?Exception("Unable?to?determine?caller's?IP.");return?ip; }public?T?GetHeaderValueAs<T>(string?headerName) {StringValues?values;if?(_httpContextAccessor.HttpContext?.Request?.Headers?.TryGetValue(headerName,?out?values)????false){string?rawValues?=?values.ToString();???//?writes?out?as?Csv?when?there?are?multiple.if?(!rawValues.IsNullOrWhitespace())return?(T)Convert.ChangeType(values.ToString(),?typeof(T));}return?default(T); }public?static?List<string>?SplitCsv(this?string?csvList,?bool?nullOrWhitespaceInputReturnsNull?=?false) {if?(string.IsNullOrWhiteSpace(csvList))return?nullOrWhitespaceInputReturnsNull???null?:?new?List<string>();return?csvList.TrimEnd(',').Split(',').AsEnumerable<string>().Select(s?=>?s.Trim()).ToList(); }public?static?bool?IsNullOrWhitespace(this?string?s) {return?String.IsNullOrWhiteSpace(s); }點評區(qū)
確實在獲取客戶端IP的時候要考慮到 X-Forwarded-For,畢竟對外的業(yè)務(wù)系統(tǒng)都是按集群為單位對外提供服務(wù)的,學(xué)習(xí)了。
總結(jié)
以上是生活随笔為你收集整理的如何在 ASP.NET CORE 中获取客户端 IP ?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 读《沟通的方法》
- 下一篇: .Net微服务实战之可观测性