HttpContext扩展类
需要引入UAParser,IPTools.Core类库a
1 public static partial class HttpContextExtension 2 { 3 /// <summary> 4 /// 是否是ajax请求 5 /// </summary> 6 /// <param name="request"></param> 7 /// <returns></returns> 8 public static bool IsAjaxRequest(this HttpRequest request) 9 { 10 if (request == null) 11 { 12 throw new ArgumentNullException(nameof(request)); 13 } 14 15 //return request.Headers.ContainsKey("X-Requested-With") && 16 // request.Headers["X-Requested-With"].Equals("XMLHttpRequest"); 17 18 return request.Headers["X-Requested-With"] == "XMLHttpRequest" || request.Headers != null && request.Headers["X-Requested-With"] == "XMLHttpRequest"; 19 } 20 21 /// <summary> 22 /// 获取客户端IP 23 /// </summary> 24 /// <param name="context"></param> 25 /// <returns></returns> 26 public static string GetClientUserIp(this HttpContext context) 27 { 28 if (context == null) return ""; 29 var result = context.Request.Headers["X-Forwarded-For"].FirstOrDefault(); 30 if (string.IsNullOrEmpty(result)) 31 { 32 result = context.Connection.RemoteIpAddress?.ToString(); 33 } 34 if (string.IsNullOrEmpty(result)) 35 throw new Exception("获取IP失败"); 36 37 if (result.Contains("::1")) 38 result = "127.0.0.1"; 39 40 result = result.Replace("::ffff:", ""); 41 result = result.Split(':')?.FirstOrDefault() ?? "127.0.0.1"; 42 result = IsIP(result) ? result : "127.0.0.1"; 43 return result; 44 } 45 46 /// <summary> 47 /// 判断是否IP 48 /// </summary> 49 /// <param name="ip"></param> 50 /// <returns></returns> 51 public static bool IsIP(string ip) 52 { 53 return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); 54 } 55 56 /// <summary> 57 /// 获取登录用户id 58 /// </summary> 59 /// <param name="context"></param> 60 /// <returns></returns> 61 public static long GetUId(this HttpContext context) 62 { 63 var uid = context.User.FindFirstValue(ClaimTypes.PrimarySid); 64 return !string.IsNullOrEmpty(uid) ? long.Parse(uid) : 0; 65 } 66 67 /// <summary> 68 /// 获取登录用户名 69 /// </summary> 70 /// <param name="context"></param> 71 /// <returns></returns> 72 public static string GetName(this HttpContext context) 73 { 74 var uid = context.User?.Identity?.Name; 75 76 return uid; 77 } 78 79 /// <summary> 80 /// 判断是否是管理员 81 /// </summary> 82 /// <param name="context"></param> 83 /// <returns></returns> 84 public static bool IsAdmin(this HttpContext context) 85 { 86 var userName = context.GetName(); 87 return userName == GlobalConstant.AdminRole; 88 } 89 90 /// <summary> 91 /// ClaimsIdentity 92 /// </summary> 93 /// <param name="context"></param> 94 /// <returns></returns> 95 public static IEnumerable<ClaimsIdentity> GetClaims(this HttpContext context) 96 { 97 return context.User?.Identities; 98 } 99 //public static int GetRole(this HttpContext context) 100 //{ 101 // var roleid = context.User.FindFirstValue(ClaimTypes.Role) ?? "0"; 102 103 // return int.Parse(roleid); 104 //} 105 106 public static string GetUserAgent(this HttpContext context) 107 { 108 return context.Request.Headers["User-Agent"]; 109 } 110 111 /// <summary> 112 /// 获取请求令牌 113 /// </summary> 114 /// <param name="context"></param> 115 /// <returns></returns> 116 public static string GetToken(this HttpContext context) 117 { 118 return context.Request.Headers["Authorization"]; 119 } 120 121 /// <summary> 122 /// 获取请求Url 123 /// </summary> 124 /// <param name="context"></param> 125 /// <returns></returns> 126 public static string GetRequestUrl(this HttpContext context) 127 { 128 return context != null ? context.Request.Path.Value : ""; 129 } 130 131 /// <summary> 132 /// 获取请求参数 133 /// </summary> 134 /// <param name="context"></param> 135 /// <returns></returns> 136 public static string GetQueryString(this HttpContext context) 137 { 138 return context != null ? context.Request.QueryString.Value : ""; 139 } 140 141 /// <summary> 142 /// 获取body请求参数 143 /// </summary> 144 /// <param name="context"></param> 145 /// <returns></returns> 146 public static string GetBody(this HttpContext context) 147 { 148 context.Request.EnableBuffering(); 149 //context.Request.Body.Seek(0, SeekOrigin.Begin); 150 //using var reader = new StreamReader(context.Request.Body, Encoding.UTF8); 151 ////需要使用异步方式才能获取 152 //return reader.ReadToEndAsync().Result; 153 string body = string.Empty; 154 var buffer = new MemoryStream(); 155 context.Request.Body.Seek(0, SeekOrigin.Begin); 156 context.Request.Body.CopyToAsync(buffer); 157 buffer.Position = 0; 158 try 159 { 160 using StreamReader streamReader = new(buffer, Encoding.UTF8); 161 body = streamReader.ReadToEndAsync().Result; 162 } 163 finally 164 { 165 buffer?.Dispose(); 166 } 167 return body; 168 } 169 170 /// <summary> 171 /// 获取浏览器信息 172 /// </summary> 173 /// <param name="context"></param> 174 /// <returns></returns> 175 public static ClientInfo GetClientInfo(this HttpContext context) 176 { 177 var str = context.GetUserAgent(); 178 var uaParser = Parser.GetDefault(); 179 ClientInfo c = uaParser.Parse(str); 180 181 return c; 182 } 183 184 /// <summary> 185 /// 根据IP获取地理位置 186 /// </summary> 187 /// <returns></returns> 188 public static string GetIpInfo(string IP) 189 { 190 var ipInfo = IpTool.Search(IP); 191 return ipInfo?.Province + "-" + ipInfo?.City + "-" + ipInfo?.NetworkOperator; 192 } 193 194 /// <summary> 195 /// 设置请求参数 196 /// </summary> 197 /// <param name="reqMethod"></param> 198 /// <param name="context"></param> 199 public static string GetRequestValue(this HttpContext context, string reqMethod) 200 { 201 string param = string.Empty; 202 203 if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod) || HttpMethods.IsDelete(reqMethod)) 204 { 205 param = context.GetBody(); 206 string regex = "(?<=\"password\":\")[^\",]*"; 207 param = Regex.Replace(param, regex, "***"); 208 } 209 if (param.IsEmpty()) 210 { 211 param = context.GetQueryString(); 212 } 213 return param; 214 } 215 }