zoukankan      html  css  js  c++  java
  • Asp.Net Core get client IP

    不废话,直接上代码,你懂得。

    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);
    }
  • 相关阅读:
    POJ 3159 :Candies 【线性差分约束 链式前向星 栈优化SPFA】
    APM系统SkyWalking介绍
    ELK架构下利用Kafka Group实现Logstash的高可用
    每个人都应有自己的产品
    几行代码养只猫,心情瞬间好多了
    Redis删除特定前缀key的优雅实现
    每个人都应有自己的作品
    Nginx的几个常用配置和技巧
    Nginx与安全有关的几个配置
    开源推荐
  • 原文地址:https://www.cnblogs.com/Javi/p/6514249.html
Copyright © 2011-2022 走看看