HttpContext擴充套件類

乐 乐——1128發表於2024-06-22
需要引入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 }

相關文章