Asp.Net Core get client IP
2017-03-07 13:14
183 查看
不废话,直接上代码,你懂得。
public string GetRequestIP(bool tryUseXForwardHeader = true) { string ip = null; // todo support new "Forwarded" header (2014) https://en.wikipedia.org/wiki/X-Forwarded-For 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.IsNullOrEmpty()) 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); }
相关文章推荐
- Asp.net core 学习笔记 ( HttpClient )
- ASP.NET Core Web API get方法获取多个值
- ASP.NET Core 搭配 Nginx 的真实IP问题
- ASP.Net Core2.1中的HttpClientFactory系列二:集成Polly处理瞬态故障
- asp.net core使用jexus部署在linux无法正确 获取远程ip的解决办法
- 用ASP.NET Core 2.0 建立规范的 REST API -- GET 和 POST
- ASP .Net 2.0 FindControl getElementById 使用
- 4 ways to send a PDF file to the IE Client in ASP.NET 2.0
- Link ASP.NET Data Grid to Microsoft Excel in the client side
- Building a Robust Web Based Email Client (WebMail) Using the IP*Works! ADO.NET Data Provider(原文)
- 从Atlas到Microsoft ASP.NET AJAX(2) - Class、JavaScript Extensions (Client BCL)
- ASP.NET 2.0 ClientScript Callback
- ASP.NET Core中使用GraphQL - 第八章 在GraphQL中处理一对多关系
- ASP.NET获取客户端IP及MAC地址
- get the password from ipclient program
- ASP.net做的IP访问限制
- ASP.NET makes uploading files from the client to the server a snap(UploadInterface.PostedFile.SaveAs)
- 允许 ASP.NET 服务器控件在 Page 中发出客户端脚本块的方法Page.RegisterClientScriptBlock 方法 [C#]
- ASP.NET获取IP与MAC[using C#]
- ASP.NET Client-Side Script FAQ (frm.Attribute.add)