using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web; namespace 落地页测试代码
{
public class WebHelper
{
#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 = ; i < encode.Length; i++)
{
string character = encode[i].ToString();
if (character == "%")
index = i;
if (i - index == || i - index == )
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=="")
return;
HttpContext.Current.Session[key] = value;
} /// <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=="")
return string.Empty;
return HttpContext.Current.Session[key] as string;
}
/// <summary>
/// 删除指定Session
/// </summary>
/// <param name="key">Session的键名</param>
public static void RemoveSession(string key)
{
if (key=="")
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(-);
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 == )
return result;
for (int i = ; i < files.Count; i++)
{
var file = files[i];
if (file.ContentLength == )
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 == )
return null;
return files[];
} #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&amp;参数2=参数值2</param>
public static string HttpWebRequest(string url, string parameters)
{
return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), true);
} /// <summary>
/// 请求网络资源,返回响应的文本
/// </summary>
/// <param name="url">网络资源地址</param>
/// <param name="parameters">提交的参数,格式:参数1=参数值1&amp;参数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, bool isPost = false,
string contentType = "application/x-www-form-urlencoded", CookieContainer cookie = null, int timeout = )
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeout;
request.CookieContainer = cookie;
if (isPost)
{
byte[] postData = encoding.GetBytes(parameters);
request.Method = "POST";
request.ContentType = contentType;
request.ContentLength = postData.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(postData, , postData.Length);
}
}
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;
} #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, @"&hellip;", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&mdash;", "", RegexOptions.IgnoreCase);
Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "", RegexOptions.IgnoreCase);
Htmlstring.Replace("<", "");
Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "", 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("&nbsp;", " ");
return html;
}
#endregion
}
}

C# 操作Session、Cookie,Url 编码解码工具类WebHelper的更多相关文章

  1. cookie的中文乱码问题【URL编码解码】

    先搞明白为什么会乱码,为什么要转码: 在tomcat 8 之前,cookie中不能直接存储中文数据.需要将中文数据转码,一般采用URL编码(%E3).在tomcat 8 之后,cookie支持中文数据 ...

  2. Delphi中处理URL编码解码

    Delphi中处理URL编码解码 一.URL简单介绍     URL是网页的地址,比方 http://www.shanhaiMy.com. Web 浏览器通过 URL 从 web server请求页面 ...

  3. sed处理url编码解码=== web日志的url处理

    URL 编码/解码方法(linux  shell实现),方法如下: 1.编码的两种方法: admin@~ 11:14:29>echo '手机' | tr -d '\n' | xxd -plain ...

  4. ASP.NET中Url编码解码

    今天遇到Url编码解码的问题,纠结了一天的时间,结果上网一查才发现太二了我们. 同事写的代码把url用HttpUtility.UrlEncode编码和解码了,本地测试没有问题,部署到服务器上就提示转码 ...

  5. 编码解码--url编码解码

    url编码解码,又叫百分号编码,是统一资源定位(URL)编码方式.URL地址(常说网址)规定了常用地数字,字母可以直接使用,另外一批作为特殊用户字符也可以直接用(/,:@等),剩下的其它所有字符必须通 ...

  6. java web url编码解码问题(下载中文名文件)

    问题描述:需要url直接访问中文名的文件,类似于在地址栏里直接输入http://localhost:8080/example/丽江旅游攻略.doc 来进行文件下载,tomcat的server.xml文 ...

  7. WebApi中对请求参数和响应内容进行URL编码解码

    项目经测试,发现从IE提交的数据,汉字会变成乱码,实验了网上很多网友说的给ajax加上contentType:"application/x-www-form-urlencoded; char ...

  8. Python学习之==>URL编码解码&if __name__ == '__main__'

    一.URL编码解码 url的编码解码需要用到标准模块urllib中的parse方法 from urllib import parse url = 'http://www.baidu.com?query ...

  9. 007-TreeMap、Map和Bean互转、BeanUtils.copyProperties(A,B)拷贝、URL编码解码、字符串补齐,随机字母数字串

    一.转换 1.1.TreeMap 有序Map 无序有序转换 使用默认构造方法: public TreeMap(Map<? extends K, ? extends V> m) 1.2.Ma ...

随机推荐

  1. React react-fastclick-alt 移动端点击

    1. Install npm install --save-dev react-fastclick-alt 2. 用法 将元素或者component放在  <FastClick>...&l ...

  2. 测试体验Centrifugo

    今天尝试用 centrifugo 来做一个在聊天室,以前用workerman做过,相对来说 workerman的配置就显得复杂多了,需要自己搭建PHP环境, 而 centrifugo 就清爽多了,官网 ...

  3. maven使用中的问题

    1.修改maven的settings.xml后,idea中配置文件指向发生了变化,指向了默认.如果maven配置文件中不是默认的,则需要根据配置文件进行修改.最好在File-Other Setting ...

  4. Codeforces Round #523 (Div. 2) D. TV Shows 模拟(多重集 先把所有区间加入多重集合)+贪心+二分

    题意:给出n个电视节目的起始和结束时间  并且租一台电视需要x +y*(b-a)  [a,b]为时段 问完整看完电视节目的最小花费是多少 思路:贪心的思想 情况1 如果新租一台电视的花费<=在空 ...

  5. DRF 商城项目 - 用户操作(收藏, 留言, 收货地址)

    个人收藏 整体逻辑类似于 个人中心 ( 个人中心的相关逻辑梳理详情  点击这里 ) 也是两个序列化组价的分流 查看收藏  ( list ) 详情指向 收藏详情 的组价 创建收藏 ( create ) ...

  6. Nginx与前端开发

    Nginx与Node.js "Nginx是一款轻量级的HTTP服务器,采用事件驱动的异步非阻塞处理方式框架,这让其具有极好的IO性能,时常用于服务端的反向代理和负载均衡." 作为前 ...

  7. Day062--django--模板,母版和继承

    1.MVC和MTV MVC C Controller : 逻辑的控制 M Model : 存取数据 V View : 信息的展示 MTV M : model ORM操作 T: Template 模板 ...

  8. C++ 左值与右值 右值引用 引用折叠 => 完美转发

    左值与右值 什么是左值?什么是右值? 在C++里没有明确定义.看了几个版本,有名字的是左值,没名字的是右值.能被&取地址的是左值,不能被&取地址的是右值.而且左值与右值可以发生转换. ...

  9. netty的基本介绍

    一.什么是netty?为什么要用netty netty是jboss提供的一个java开源框架,netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可用性的网络服务器和客户端程 ...

  10. crm 一级菜单排序,二级菜单选中并且展开,非菜单权限的归属,权限粒度控制到按钮级别

    排序 /rbac/templatetags/rbac.py from django import template from django.conf import settings import re ...