123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637 |
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Web;
- using System;
- using System.Text.RegularExpressions;
- using System.Web.SessionState;
- using System.Net.Security;
- using System.Security.Cryptography.X509Certificates;
- namespace LeaRun.Util
- {
- /// <summary>
- /// Web操作
- /// </summary>
- public static class WebHelper
- {
- #region Host(获取主机名)
- /// <summary>
- /// 获取主机名,即域名,
- /// 范例:用户输入网址http://www.a.com/b.htm?a=1&b=2,
- /// 返回值为: www.a.com
- /// </summary>
- public static string Host
- {
- get
- {
- return HttpContext.Current.Request.Url.Host;
- }
- }
- #endregion
- #region ResolveUrl(解析相对Url)
- /// <summary>
- /// 解析相对Url
- /// </summary>
- /// <param name="relativeUrl">相对Url</param>
- public static string ResolveUrl(string relativeUrl)
- {
- if (string.IsNullOrWhiteSpace(relativeUrl))
- return string.Empty;
- relativeUrl = relativeUrl.Replace("\\", "/");
- if (relativeUrl.StartsWith("/"))
- return relativeUrl;
- if (relativeUrl.Contains("://"))
- return relativeUrl;
- return VirtualPathUtility.ToAbsolute(relativeUrl);
- }
- #endregion
- #region HtmlEncode(对html字符串进行编码)
- /// <summary>
- /// 对html字符串进行编码
- /// </summary>
- /// <param name="html">html字符串</param>
- public static string HtmlEncode(string html)
- {
- return HttpUtility.HtmlEncode(html);
- }
- /// <summary>
- /// 对html字符串进行解码
- /// </summary>
- /// <param name="html">html字符串</param>
- public static string HtmlDecode(string html)
- {
- return HttpUtility.HtmlDecode(html);
- }
- #endregion
- #region UrlEncode(对Url进行编码)
- /// <summary>
- /// 对Url进行编码
- /// </summary>
- /// <param name="url">url</param>
- /// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
- public static string UrlEncode(string url, bool isUpper = false)
- {
- return UrlEncode(url, Encoding.UTF8, isUpper);
- }
- /// <summary>
- /// 对Url进行编码
- /// </summary>
- /// <param name="url">url</param>
- /// <param name="encoding">字符编码</param>
- /// <param name="isUpper">编码字符是否转成大写,范例,"http://"转成"http%3A%2F%2F"</param>
- public static string UrlEncode(string url, Encoding encoding, bool isUpper = false)
- {
- var result = HttpUtility.UrlEncode(url, encoding);
- if (!isUpper)
- return result;
- return GetUpperEncode(result);
- }
- /// <summary>
- /// 获取大写编码字符串
- /// </summary>
- private static string GetUpperEncode(string encode)
- {
- var result = new StringBuilder();
- int index = int.MinValue;
- for (int i = 0; i < encode.Length; i++)
- {
- string character = encode[i].ToString();
- if (character == "%")
- index = i;
- if (i - index == 1 || i - index == 2)
- character = character.ToUpper();
- result.Append(character);
- }
- return result.ToString();
- }
- #endregion
- #region UrlDecode(对Url进行解码)
- /// <summary>
- /// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
- /// </summary>
- /// <param name="url">url</param>
- public static string UrlDecode(string url)
- {
- return HttpUtility.UrlDecode(url);
- }
- /// <summary>
- /// 对Url进行解码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码
- /// </summary>
- /// <param name="url">url</param>
- /// <param name="encoding">字符编码,对于javascript的encodeURIComponent函数编码参数,应使用utf-8字符编码来解码</param>
- public static string UrlDecode(string url, Encoding encoding)
- {
- return HttpUtility.UrlDecode(url, encoding);
- }
- #endregion
- #region Session操作
- /// <summary>
- /// 写Session
- /// </summary>
- /// <typeparam name="T">Session键值的类型</typeparam>
- /// <param name="key">Session的键名</param>
- /// <param name="value">Session的键值</param>
- public static void WriteSession<T>(string key, T value)
- {
- //if (key.IsEmpty())
- // return;
- HttpContext.Current.Session[key] = value;
- HttpContext.Current.Session.Timeout = 60;//设置默认的时间60分钟
- }
- /// <summary>
- /// 写Session
- /// </summary>
- /// <param name="key">Session的键名</param>
- /// <param name="value">Session的键值</param>
- public static void WriteSession(string key, string value)
- {
- WriteSession<string>(key, value);
- }
- /// <summary>
- /// 读取Session的值
- /// </summary>
- /// <param name="key">Session的键名</param>
- public static string GetSession(string key)
- {
- //if (key.IsEmpty())
- // return string.Empty;
- if (HttpContext.Current.Session[key] != null)
- return HttpContext.Current.Session[key] as string;
- else
- return "";
- }
- /// <summary>
- /// 删除指定Session
- /// </summary>
- /// <param name="key">Session的键名</param>
- public static void RemoveSession(string key)
- {
- //if (key.IsEmpty())
- // return;
- HttpContext.Current.Session.Contents.Remove(key);
- }
- #endregion
- #region Cookie操作
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="strValue">值</param>
- public static void WriteCookie(string strName, string strValue)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.Value = strValue;
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="strValue">值</param>
- /// <param name="strValue">过期时间(分钟)</param>
- public static void WriteCookie(string strName, string strValue, int expires)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.Value = strValue;
- cookie.Expires = DateTime.Now.AddMinutes(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 读cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <returns>cookie值</returns>
- public static string GetCookie(string strName)
- {
- if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
- {
- return HttpContext.Current.Request.Cookies[strName].Value.ToString();
- }
- return "";
- }
- /// <summary>
- /// 删除Cookie对象
- /// </summary>
- /// <param name="CookiesName">Cookie对象名称</param>
- public static void RemoveCookie(string CookiesName)
- {
- HttpCookie objCookie = new HttpCookie(CookiesName.Trim());
- objCookie.Expires = DateTime.Now.AddYears(-5);
- HttpContext.Current.Response.Cookies.Add(objCookie);
- }
- #endregion
- #region GetFileControls(获取客户端文件控件集合)
- /// <summary>
- /// 获取有效客户端文件控件集合,文件控件必须上传了内容,为空将被忽略,
- /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
- /// </summary>
- public static List<HttpPostedFile> GetFileControls()
- {
- var result = new List<HttpPostedFile>();
- var files = HttpContext.Current.Request.Files;
- if (files.Count == 0)
- return result;
- for (int i = 0; i < files.Count; i++)
- {
- var file = files[i];
- if (file.ContentLength == 0)
- continue;
- result.Add(files[i]);
- }
- return result;
- }
- #endregion
- #region GetFileControl(获取第一个有效客户端文件控件)
- /// <summary>
- /// 获取第一个有效客户端文件控件,文件控件必须上传了内容,为空将被忽略,
- /// 注意:Form标记必须加入属性 enctype="multipart/form-data",服务器端才能获取客户端file控件.
- /// </summary>
- public static HttpPostedFile GetFileControl()
- {
- var files = GetFileControls();
- if (files == null || files.Count == 0)
- return null;
- return files[0];
- }
- #endregion
- #region HttpWebRequest(请求网络资源)
- /// <summary>
- /// 请求网络资源,返回响应的文本
- /// </summary>
- /// <param name="url">网络资源地址</param>
- public static string HttpWebRequest(string url)
- {
- return HttpWebRequest(url, string.Empty, Encoding.GetEncoding("utf-8"));
- }
- /// <summary>
- /// 请求网络资源,返回响应的文本
- /// </summary>
- /// <param name="url">网络资源Url地址</param>
- /// <param name="parameters">提交的参数,格式:参数1=参数值1&参数2=参数值2</param>
- public static string HttpWebRequest(string url, string parameters)
- {
- return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), "POST");
- }
- /// <summary>
- /// 请求网络资源,返回响应的文本
- /// </summary>
- /// <param name="url">网络资源Url地址</param>
- /// <param name="parameters"></param>
- public static string HttpWebRequest(string url, string parameters, string contentType, string Authorization, string app_key)
- {
- return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), "POST", contentType, Authorization, app_key);
- }
- /// <summary>
- /// 请求网络资源,返回响应的文本
- /// </summary>
- /// <param name="url">网络资源Url地址</param>
- /// <param name="parameters"></param>
- public static string HttpWebRequest(string url, string parameters, string mehtod, string contentType, string Authorization, string app_key)
- {
- return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), mehtod, contentType, Authorization, app_key);
- }
- /// <summary>
- /// 请求网络资源,返回响应的文本
- /// </summary>
- /// <param name="url">网络资源地址</param>
- /// <param name="parameters">提交的参数,格式:参数1=参数值1&参数2=参数值2</param>
- /// <param name="encoding">字符编码</param>
- /// <param name="isPost">是否Post提交</param>
- /// <param name="contentType">内容类型</param>
- /// <param name="cookie">Cookie容器</param>
- /// <param name="timeout">超时时间</param>
- public static string HttpWebRequest(string url, string parameters, Encoding encoding, string mehtod = "POST",
- string contentType = "application/x-www-form-urlencoded", string Authorization = null, string app_key = null, CookieContainer cookie = null, int timeout = 120000)
- {
- HttpWebRequest request = null;
- try
- {
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
- //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
- ////X509Certificate cerCaiShang = new X509Certificate(System.Web.HttpContext.Current.Server.MapPath(Config.GetValue("NB_PfxPath")), Config.GetValue("NB_PfxKey"));
- ////X509Certificate2 cerCaiShang = GetSentosaCertificate();
- //X509Certificate2 cerCaiShang = new X509Certificate2(Config.GetValue("NB_PfxPath"), Config.GetValue("NB_PfxKey"));
- //request = WebRequest.Create(url) as HttpWebRequest;
- //request.ClientCertificates.Add(cerCaiShang);
- //request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Timeout = timeout;
- if (!string.IsNullOrEmpty(Authorization))
- {
- request.Headers["Authorization"] = Authorization;
- }
- if (!string.IsNullOrEmpty(app_key))
- {
- request.Headers["app_key"] = app_key;
- }
- request.CookieContainer = cookie;
- request.ContentType = contentType;
- request.Method = mehtod;
- if (mehtod == "POST")
- {
- byte[] postData = encoding.GetBytes(parameters);
- request.Method = "POST";
- request.ContentType = contentType;
- request.ContentLength = postData.Length;
- using (Stream stream = request.GetRequestStream())
- {
- stream.Write(postData, 0, postData.Length);
- }
- }
- if (mehtod == "PUT")
- {
- using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
- {
- requestStream.Write(parameters);
- }
- }
- var response = (HttpWebResponse)request.GetResponse();
- string result;
- using (Stream stream = response.GetResponseStream())
- {
- if (stream == null)
- return string.Empty;
- using (var reader = new StreamReader(stream, encoding))
- {
- result = reader.ReadToEnd();
- }
- }
- return result;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- {
- return true;
- }
- private static X509Certificate2 GetSentosaCertificate()
- {
- X509Store userCaStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
- try
- {
- userCaStore.Open(OpenFlags.ReadOnly);
- X509Certificate2Collection certificatesInStore = userCaStore.Certificates;
- X509Certificate2Collection findResult = certificatesInStore.Find(X509FindType.FindBySubjectName, "server", true);
- X509Certificate2 clientCertificate = null;
- if (findResult.Count == 1)
- {
- clientCertificate = findResult[0];
- }
- else
- {
- throw new Exception("Unable to locate the correct client certificate.");
- }
- return clientCertificate;
- }
- catch
- {
- throw;
- }
- finally
- {
- userCaStore.Close();
- }
- }
- #endregion
- #region 去除HTML标记
- /// <summary>
- /// 去除HTML标记
- /// </summary>
- /// <param name="NoHTML">包括HTML的源码 </param>
- /// <returns>已经去除后的文字</returns>
- public static string NoHtml(string Htmlstring)
- {
- //删除脚本
- Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
- //删除HTML
- Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"…", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"—", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"“", "", RegexOptions.IgnoreCase);
- Htmlstring.Replace("<", "");
- Htmlstring = Regex.Replace(Htmlstring, @"”", "", RegexOptions.IgnoreCase);
- Htmlstring.Replace(">", "");
- Htmlstring.Replace("\r\n", "");
- Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
- return Htmlstring;
- }
- #endregion
- #region 格式化文本(防止SQL注入)
- /// <summary>
- /// 格式化文本(防止SQL注入)
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string Formatstr(string html)
- {
- System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- System.Text.RegularExpressions.Regex regex10 = new System.Text.RegularExpressions.Regex(@"select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- System.Text.RegularExpressions.Regex regex11 = new System.Text.RegularExpressions.Regex(@"update", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- System.Text.RegularExpressions.Regex regex12 = new System.Text.RegularExpressions.Regex(@"delete", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- html = regex1.Replace(html, ""); //过滤<script></script>标记
- html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
- html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
- html = regex4.Replace(html, ""); //过滤iframe
- html = regex10.Replace(html, "s_elect");
- html = regex11.Replace(html, "u_pudate");
- html = regex12.Replace(html, "d_elete");
- html = html.Replace("'", "’");
- html = html.Replace(" ", " ");
- return html;
- }
- #endregion
- #region 根据OneNet平台的鉴权修改Http请求
- /// <summary>
- /// 请求网络资源,返回响应的文本
- /// </summary>
- /// <param name="url">网络资源地址</param>
- /// <param name="parameters">提交的参数,格式:参数1=参数值1&参数2=参数值2</param>
- /// <param name="encoding">字符编码</param>
- /// <param name="isPost">是否Post提交</param>
- /// <param name="contentType">内容类型</param>
- /// <param name="cookie">Cookie容器</param>
- /// <param name="timeout">超时时间</param>
- public static string HttpWebRequest_oneNet(string url, string parameters, Encoding encoding, string mehtod = "POST",
- string contentType = "application/x-www-form-urlencoded", string Authorization = null, string api_key = null, CookieContainer cookie = null, int timeout = 120000)
- {
- mehtod = mehtod.ToUpper();
- HttpWebRequest request = null;
- try
- {
- //如果是发送HTTPS请求
- if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
- {
- //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
- //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
- ////X509Certificate cerCaiShang = new X509Certificate(System.Web.HttpContext.Current.Server.MapPath(Config.GetValue("NB_PfxPath")), Config.GetValue("NB_PfxKey"));
- ////X509Certificate2 cerCaiShang = GetSentosaCertificate();
- //X509Certificate2 cerCaiShang = new X509Certificate2(Config.GetValue("NB_PfxPath"), Config.GetValue("NB_PfxKey"));
- //request = WebRequest.Create(url) as HttpWebRequest;
- //request.ClientCertificates.Add(cerCaiShang);
- //request.ProtocolVersion = HttpVersion.Version10;
- }
- else
- {
- request = WebRequest.Create(url) as HttpWebRequest;
- }
- request.Timeout = timeout;
- if (!string.IsNullOrEmpty(Authorization))
- {
- request.Headers["Authorization"] = Authorization;
- }
- if (!string.IsNullOrEmpty(api_key))
- {
- request.Headers["api-key"] = api_key;
- }
- request.CookieContainer = cookie;
- request.ContentType = contentType;
- request.Method = mehtod;
- if (mehtod == "POST")
- {
- byte[] postData = encoding.GetBytes(parameters);
- request.Method = "POST";
- request.ContentType = contentType;
- request.ContentLength = postData.Length;
- using (Stream stream = request.GetRequestStream())
- {
- stream.Write(postData, 0, postData.Length);
- }
- }
- if (mehtod == "PUT")
- {
- using (StreamWriter requestStream = new StreamWriter(request.GetRequestStream()))
- {
- requestStream.Write(parameters);
- }
- }
- var response = (HttpWebResponse)request.GetResponse();
- string result;
- using (Stream stream = response.GetResponseStream())
- {
- if (stream == null)
- return string.Empty;
- using (var reader = new StreamReader(stream, encoding))
- {
- result = reader.ReadToEnd();
- }
- }
- return result;
- }
- catch (Exception ex)
- {
- return "接口调用错误";
- }
- }
- /// <summary>
- /// 请求网络资源,返回响应的文本 HttpWebRequest_oneNet(string url, string parameters, string mehtod, string contentType, string Authorization, string api_key)
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="parameters">参数</param>
- /// <param name="mehtod">请求方式</param>
- /// <param name="contentType"></param>
- /// <param name="Authorization"></param>
- /// <param name="api_key"></param>
- /// <returns></returns>
- //public static string HttpWebRequest_oneNet(string url, string parameters, string mehtod, string contentType, string Authorization, string api_key)
- //{
- // if (api_key == null)
- // {
- // api_key = Config.GetValue("APIkey");
- // }
- // return HttpWebRequest_oneNet(url, parameters, Encoding.GetEncoding("utf-8"), mehtod, contentType, Authorization, api_key);
- //}
- #endregion
- }
- }
|