最详细的ASP.NET微信JS-SDK支付代码
程序员文章站
2023-11-18 17:44:40
本文实例为大家分享了微信js sdk支付的具体代码,供大家参考,具体内容如下
模型层实体类:
public class jsentities
{
//...
本文实例为大家分享了微信js sdk支付的具体代码,供大家参考,具体内容如下
模型层实体类:
public class jsentities { /// <summary> /// 公众号id /// </summary> public string appid { get; set; } /// <summary> /// 时间戳 /// </summary> public string timestamp { get; set; } /// <summary> /// 随机字符串 /// </summary> public string noncestr { get; set; } /// <summary> /// 订单详情扩展字符串 /// </summary> public string package { get; set; } /// <summary> /// 签名类型 /// </summary> public string signtype { get; set; } /// <summary> /// 签名 /// </summary> public string paysign { get; set; } }
public class unifyentities { /// <summary> /// 公众账号id /// </summary> public string appid { get; set; } /// <summary> /// 微信支付分配的商户号 /// </summary> public string mch_id { get; set; } /// <summary> /// 微信支付分配的终端设备号 /// </summary> public string device_info { get; set; } /// <summary> /// 随机字符串,不长于32位 /// </summary> public string nonce_str { get; set; } /// <summary> /// 签名 /// </summary> public string sign { get; set; } /// <summary> /// 商品描述最大长度127 /// </summary> public string body { get; set; } /// <summary> /// 附加数据,原样返回 /// </summary> public string attach { get; set; } /// <summary> /// 商户系统内部的订单号,32 个字符内、可包含字母,确保在商户系统唯一,详细说明 /// </summary> public string out_trade_no { get; set; } /// <summary> /// 订单总金额,单位为分,不能带小数点 /// </summary> public string total_fee { get; set; } /// <summary> /// 终端ip /// </summary> public string spbill_create_ip { get; set; } /// <summary> /// 交易起始时间 /// </summary> public string time_start { get; set; } /// <summary> /// 交易结束时间 /// </summary> public string time_expire { get; set; } /// <summary> /// 接收微信支付成功通知 /// </summary> public string notify_url { get; set; } /// <summary> /// jsapi、native、app /// </summary> public string trade_type { get; set; } /// <summary> /// 用户在商户appid下的唯一标识,trade_type为jsapi 时,此参数必传 /// </summary> public string openid { get; set; } /// <summary> /// 只在 trade_type 为 native 时需要填写。此id为二维码中包含的商品id,商户自行维护。 /// </summary> public string product_id { get; set; } }
public class unifyreceive { /// <summary> /// success/fail此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断 /// </summary> public string return_code { get; set; } /// <summary> /// 返回信息,如非空,为错误原因 /// </summary> public string return_msg { get; set; } /// <summary> /// 微信分配的公众账号id /// </summary> public string appid { get; set; } /// <summary> /// 微信支付分配的商户号 /// </summary> public string mch_id { get; set; } /// <summary> /// 随机字符串,不长于32位 /// </summary> public string nonce_str { get; set; } /// <summary> /// 签名 /// </summary> public string sign { get; set; } /// <summary> /// 业务结果 /// </summary> public string result_code { get; set; } /// <summary> /// 预支付id /// </summary> public string prepay_id { get; set; } /// <summary> /// 交易类型 /// </summary> public string trade_type { get; set; } /// <summary> /// 二维码链接 /// </summary> public string code_url { get; set; } public unifyreceive(string xml) { xelement doc = xelement.parse(xml); return_code = doc.element("return_code").value; return_msg = doc.element("return_msg").value; if (return_code == "success") { appid = doc.element("appid").value; mch_id = doc.element("mch_id").value; nonce_str = doc.element("nonce_str").value; sign = doc.element("sign").value; result_code = doc.element("result_code").value; if (result_code == "success") { trade_type = doc.element("trade_type").value; prepay_id = doc.element("prepay_id").value; if (trade_type == "native") { code_url = doc.element("code_url").value; } trade_type = doc.element("trade_type").value; } } } }
testjs.aspx内容:
<%@ page language="c#" autoeventwireup="true" codebehind="jspay.aspx.cs" inherits="wechatpaydemo.jspay" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title></title> <script src="http://code.jquery.com/jquery-1.9.0.js"></script> <script src="scripts/wxpay.js"></script> <script> $(function () { $("#submit").click(function () { var oid ="<%=openid%>"; alert(oid); $.get("wxpay/wxpay.ashx?action=jspayparam", { body: $("#body").val(), total_fee: $("#price").val(), out_trade_no: $("#order").val(), trade_type: "jsapi", msgid: "<%=openid%>" }, function (data) { wxpay.pay(data.appid, data.timestamp, data.noncestr, data.package, data.signtype, data.paysign, function () { alert("支付成功"); }); }, "json"); }); }) </script> </head> <body> <form id="form1" runat="server"> <div> 商品描述:<input type="text" id="body" /> 商品价格:<input type="text" id="price" /> 订单号:<input type="text" id="order" /> <input type="button" value="提交订单" id="submit" /> </div> </form> </body> </html>
jspay.aspx.cs代码:
public partial class jspay : system.web.ui.page { public string openid = ""; protected void page_load(object sender, eventargs e) { string code = request["code"]; if (string.isnullorempty(code)) { //如果code没获取成功,重新拉取一遍 getauthurl("wxxxxxxxxxxxxxxxxxxxxxxx", "http://www.china101.net/jspay.aspx"); } openid = getopenid("wxxxxxxxxxxxxxxxxxxxxxxx", "dsdssdsdsdsdsdsdsdsdsd", jkrequest.getquerystring("code"), () => { }); } public string getopenid(string appid, string secret, string code, action callback) { try { string retdata = utils.httpget(string.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code)); .loghelper.writefile(retdata); jobject jobj = (jobject)jsonconvert.deserializeobject(retdata); string openid = jobj.value<string>("openid"); return openid; } catch (exception) { callback(); return ""; } // return getuserinfo(access_token, openid); } /// <summary> /// 获取鉴权地址 /// </summary> /// <param name="appid"></param> /// <param name="redirect_url"></param> /// <returns></returns> public void getauthurl(string appid, string redirect_url) { response.redirect(string.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123#wechat_redirect", appid, utils.urlencode(redirect_url))); } }
wxpay.ashx代码:
/// <summary> /// wxpay 的摘要说明 /// </summary> public class wxpay : ihttphandler { /// <summary> /// 公众账号id /// </summary> private string appid = "wxxxxxxxxxxxxxxxx"; /// <summary> /// 商户号 /// </summary> private string mch_id = "12333333333"; /// <summary> /// 通知url /// </summary> private string notify_url = "http://www.china101.net/notify2.aspx"; /// <summary> /// 密钥 /// </summary> private string key = "chinapagexxxxxxxxxxxxx"; public void processrequest(httpcontext context) { string action = jkrequest.getquerystring("action"); switch (action) { case "unifysign": getunifysign(context); break; case "jspayparam": getjspayparam(context); break; case "nativedynamic": getpayqr(context); break; } } #region 获取js支付参数 void getjspayparam(httpcontext context) { jsentities jsentities = new jsentities() { appid = appid, noncestr = .utils.getrandom(), package = string.format("prepay_id={0}", getprepayid(context)), signtype = "md5", timestamp = .utils.convertdatetimeint(datetime.now).tostring() }; string url, sign; string xmlstr = .utils.getunifyrequestxml<jsentities>(jsentities, key, out url, out sign); loghelper.writefile(xmlstr); jsentities.paysign = sign; context.response.write(jsonconvert.serializeobject(jsentities)); } #endregion #region 获取预支付id //-------------------------------------------------------------------------- string getprepayid(httpcontext context) { string xml; getunifysign(context, out xml); loghelper.writefile("getprepayid---71--" + xml); unifyreceive unifyreceive = new unifyreceive(.utils.httppost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml)); loghelper.writefile("unifyreceive---73--" + unifyreceive.prepay_id); return unifyreceive.prepay_id; } #endregion #region 获取统一签名 void getunifysign(httpcontext context) { string xml; context.response.write(getunifysign(context, out xml)); } #endregion #region 获取统一签名 string getunifysign(httpcontext context, out string xml) { string url, sign; xml = wxpayhelper.utils.getunifyurlxml<unifyentities>(getunifyentities(context), key, out url, out sign); return sign; } #endregion #region 获取二维码 void getpayqr(httpcontext context) { string url = getpayurl(context); wxpayhelper.utils.getqrcode(url); } #endregion #region 获取二维码链接 string getpayurl(httpcontext context) { string xml; getunifysign(context, out xml); wxpayhelper.utils.writetxt(xml); unifyreceive unifyreceive = new unifyreceive(wxpayhelper.utils.httppost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml)); return unifyreceive.code_url; } #endregion #region 获取统一支付接口参数对象 unifyentities getunifyentities(httpcontext context) { string msgid = jkrequest.getquerystring("msgid"); loghelper.writefile("115---------"+msgid); unifyentities unify = new unifyentities { appid = appid, body = jkrequest.getquerystring("body"), mch_id = mch_id, nonce_str = wxpayhelper.utils.getrandom(), out_trade_no = jkrequest.getquerystring("out_trade_no"), notify_url = notify_url, spbill_create_ip = jkrequest.getip(), trade_type = jkrequest.getquerystring("trade_type"), total_fee = jkrequest.getquerystring("total_fee") }; if (unify.trade_type == "native") { unify.product_id = msgid; } else { unify.openid = msgid; } return unify; } #endregion public bool isreusable { get { return false; } } }
utils.cs代码:
public class utils { #region md5加密 public static string md5(string pwd) { md5 md5 = new md5cryptoserviceprovider(); byte[] data = system.text.encoding.default.getbytes(pwd); byte[] md5data = md5.computehash(data); md5.clear(); string str = ""; for (int i = 0; i < md5data.length; i++) { str += md5data[i].tostring("x").padleft(2, '0'); } return str; } /// <summary> /// 获取文件的md5 /// </summary> /// <param name="filepath">文件路径,url路径</param> /// <returns>md5字符串</returns> string getmd5hashfromfile(string filepath) { try { webclient wc = new webclient(); var file = wc.openread(new uri(filepath)); system.security.cryptography.md5 md5 = new system.security.cryptography.md5cryptoserviceprovider(); byte[] retval = md5.computehash(file); file.close(); stringbuilder sb = new stringbuilder(); for (int i = 0; i < retval.length; i++) { sb.append(retval[i].tostring("x2")); } return sb.tostring(); } catch (exception ex) { throw new exception("getmd5hashfromfile() fail,error:" + ex.message); } } #endregion #region 对象转换处理 /// <summary> /// 判断对象是否为int32类型的数字 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool isnumeric(object expression) { if (expression != null) return isnumeric(expression.tostring()); return false; } /// <summary> /// 判断对象是否为int32类型的数字 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool isnumeric(string expression) { if (expression != null) { string str = expression; if (str.length > 0 && str.length <= 11 && regex.ismatch(str, @"^[-]?[0-9]*[.]?[0-9]*$")) { if ((str.length < 10) || (str.length == 10 && str[0] == '1') || (str.length == 11 && str[0] == '-' && str[1] == '1')) return true; } } return false; } /// <summary> /// 是否为double类型 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool isdouble(object expression) { if (expression != null) return regex.ismatch(expression.tostring(), @"^([0-9])[0-9]*(\.\w*)?$"); return false; } /// <summary> /// 检测是否符合email格式 /// </summary> /// <param name="stremail">要判断的email字符串</param> /// <returns>判断结果</returns> public static bool isvalidemail(string stremail) { return regex.ismatch(stremail, @"^[\w\.]+([-]\w+)*@[a-za-z0-9-_]+[\.][a-za-z0-9-_]"); } public static bool isvaliddoemail(string stremail) { return regex.ismatch(stremail, @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-za-z]{2,4}|[0-9]{1,3})(\]?)$"); } /// <summary> /// 检测是否是正确的url /// </summary> /// <param name="strurl">要验证的url</param> /// <returns>判断结果</returns> public static bool isurl(string strurl) { return regex.ismatch(strurl, @"^(http|https)\://([a-za-z0-9\.\-]+(\:[a-za-z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-za-z0-9\-]+\.)*[a-za-z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-za-z]{1,10}))(\:[0-9]+)*(/($|[a-za-z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); } /// <summary> /// 将字符串转换为数组 /// </summary> /// <param name="str">字符串</param> /// <returns>字符串数组</returns> public static string[] getstrarray(string str) { return str.split(new char[',']); } /// <summary> /// 将数组转换为字符串 /// </summary> /// <param name="list">list</param> /// <param name="speater">分隔符</param> /// <returns>string</returns> public static string getarraystr(list<string> list, string speater) { stringbuilder sb = new stringbuilder(); for (int i = 0; i < list.count; i++) { if (i == list.count - 1) { sb.append(list[i]); } else { sb.append(list[i]); sb.append(speater); } } return sb.tostring(); } /// <summary> /// object型转换为bool型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool strtobool(object expression, bool defvalue) { if (expression != null) return strtobool(expression, defvalue); return defvalue; } /// <summary> /// string型转换为bool型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的bool类型结果</returns> public static bool strtobool(string expression, bool defvalue) { if (expression != null) { if (string.compare(expression, "true", true) == 0) return true; else if (string.compare(expression, "false", true) == 0) return false; } return defvalue; } /// <summary> /// 将对象转换为int32类型 /// </summary> /// <param name="expression">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int objtoint(object expression, int defvalue) { if (expression != null) return strtoint(expression.tostring(), defvalue); return defvalue; } /// <summary> /// 将字符串转换为int32类型 /// </summary> /// <param name="expression">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int strtoint(string expression, int defvalue) { if (string.isnullorempty(expression) || expression.trim().length >= 11 || !regex.ismatch(expression.trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$")) return defvalue; int rv; if (int32.tryparse(expression, out rv)) return rv; return convert.toint32(strtofloat(expression, defvalue)); } /// <summary> /// object型转换为decimal型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的decimal类型结果</returns> public static decimal objtodecimal(object expression, decimal defvalue) { if (expression != null) return strtodecimal(expression.tostring(), defvalue); return defvalue; } /// <summary> /// string型转换为decimal型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的decimal类型结果</returns> public static decimal strtodecimal(string expression, decimal defvalue) { if ((expression == null) || (expression.length > 10)) return defvalue; decimal intvalue = defvalue; if (expression != null) { bool isdecimal = regex.ismatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); if (isdecimal) decimal.tryparse(expression, out intvalue); } return intvalue; } /// <summary> /// object型转换为float型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float objtofloat(object expression, float defvalue) { if (expression != null) return strtofloat(expression.tostring(), defvalue); return defvalue; } /// <summary> /// string型转换为float型 /// </summary> /// <param name="strvalue">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static float strtofloat(string expression, float defvalue) { if ((expression == null) || (expression.length > 10)) return defvalue; float intvalue = defvalue; if (expression != null) { bool isfloat = regex.ismatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$"); if (isfloat) float.tryparse(expression, out intvalue); } return intvalue; } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static datetime strtodatetime(string str, datetime defvalue) { if (!string.isnullorempty(str)) { datetime datetime; if (datetime.tryparse(str, out datetime)) return datetime; } return defvalue; } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="str">要转换的字符串</param> /// <returns>转换后的int类型结果</returns> public static datetime strtodatetime(string str) { return strtodatetime(str, datetime.now); } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="obj">要转换的对象</param> /// <returns>转换后的int类型结果</returns> public static datetime objecttodatetime(object obj) { return strtodatetime(obj.tostring()); } /// <summary> /// 将对象转换为日期时间类型 /// </summary> /// <param name="obj">要转换的对象</param> /// <param name="defvalue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static datetime objecttodatetime(object obj, datetime defvalue) { return strtodatetime(obj.tostring(), defvalue); } /// <summary> /// 将对象转换为字符串 /// </summary> /// <param name="obj">要转换的对象</param> /// <returns>转换后的string类型结果</returns> public static string objecttostr(object obj) { if (obj == null) return ""; return obj.tostring().trim(); } /// <summary> /// 判断是否邮箱 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool isemail(string expression) { return regex.ismatch(expression, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-za-z]{2,4}|[0-9]{1,3})(\]?)$"); } /// <summary> /// 判断是否手机 /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool ismobile(string expression) { return regex.ismatch(expression, @"^1[3|4|5|6|7|8|9][0-9]{9}$"); } public static bool isphone(string telphone) { regex regex = new regex(@"^(\d{3,4}-)?\d{6,8}$"); return regex.ismatch(telphone); } #endregion #region 分割字符串 /// <summary> /// 分割字符串 /// </summary> public static string[] splitstring(string strcontent, string strsplit) { if (!string.isnullorempty(strcontent)) { if (strcontent.indexof(strsplit) < 0) return new string[] { strcontent }; return regex.split(strcontent, regex.escape(strsplit), regexoptions.ignorecase); } else return new string[0] { }; } /// <summary> /// 分割字符串 /// </summary> /// <returns></returns> public static string[] splitstring(string strcontent, string strsplit, int count) { string[] result = new string[count]; string[] splited = splitstring(strcontent, strsplit); for (int i = 0; i < count; i++) { if (i < splited.length) result[i] = splited[i]; else result[i] = string.empty; } return result; } #endregion #region 删除最后结尾的一个逗号 /// <summary> /// 删除最后结尾的一个逗号 /// </summary> public static string dellastcomma(string str) { if (str.length < 1) { return ""; } return str.substring(0, str.lastindexof(",")); } #endregion #region 删除最后结尾的指定字符后的字符 /// <summary> /// 删除最后结尾的指定字符后的字符 /// </summary> public static string dellastchar(string str, string strchar) { if (string.isnullorempty(str)) return ""; if (str.lastindexof(strchar) >= 0 && str.lastindexof(strchar) == str.length - 1) { return str.substring(0, str.lastindexof(strchar)); } return str; } #endregion #region 生成指定长度的字符串 /// <summary> /// 生成指定长度的字符串,即生成strlong个str字符串 /// </summary> /// <param name="strlong">生成的长度</param> /// <param name="str">以str生成字符串</param> /// <returns></returns> public static string stringofchar(int strlong, string str) { string returnstr = ""; for (int i = 0; i < strlong; i++) { returnstr += str; } return returnstr; } #endregion #region 生成日期随机码 /// <summary> /// 生成日期随机码 /// </summary> /// <returns></returns> public static string getramcode() { #region return datetime.now.tostring("yyyymmddhhmmssffff"); #endregion } #endregion #region 生成随机字母或数字 /// <summary> /// 生成随机数字 /// </summary> /// <param name="length">生成长度</param> /// <returns></returns> public static string number(int length) { return number(length, false); } /// <summary> /// 生成随机数字 /// </summary> /// <param name="length">生成长度</param> /// <param name="sleep">是否要在生成前将当前线程阻止以避免重复</param> /// <returns></returns> public static string number(int length, bool sleep) { if (sleep) system.threading.thread.sleep(3); string result = ""; system.random random = new random(); for (int i = 0; i < length; i++) { result += random.next(10).tostring(); } return result; } /// <summary> /// 生成随机字母字符串(数字字母混和) /// </summary> /// <param name="codecount">待生成的位数</param> public static string getcheckcode(int codecount) { string str = string.empty; int rep = 0; long num2 = datetime.now.ticks + rep; rep++; random random = new random(((int)(((ulong)num2) & 0xffffffffl)) | ((int)(num2 >> rep))); for (int i = 0; i < codecount; i++) { char ch; int num = random.next(); if ((num % 2) == 0) { ch = (char)(0x30 + ((ushort)(num % 10))); } else { ch = (char)(0x41 + ((ushort)(num % 0x1a))); } str = str + ch.tostring(); } return str; } /// <summary> /// 根据日期和随机码生成订单号 /// </summary> /// <returns></returns> public static string getordernumber() { string num = datetime.now.tostring("yymmddhhmmss");//yyyymmddhhmmssms return num + number(2).tostring(); } private static int next(int numseeds, int length) { byte[] buffer = new byte[length]; system.security.cryptography.rngcryptoserviceprovider gen = new system.security.cryptography.rngcryptoserviceprovider(); gen.getbytes(buffer); uint randomresult = 0x0;//这里用uint作为生成的随机数 for (int i = 0; i < length; i++) { randomresult |= ((uint)buffer[i] << ((length - 1 - i) * 8)); } return (int)(randomresult % numseeds); } #endregion #region 截取字符长度 /// <summary> /// 截取字符长度 /// </summary> /// <param name="inputstring">字符</param> /// <param name="len">长度</param> /// <returns></returns> public static string cutstring(string inputstring, int len) { if (string.isnullorempty(inputstring)) return ""; inputstring = drophtml(inputstring); asciiencoding ascii = new asciiencoding(); int templen = 0; string tempstring = ""; byte[] s = ascii.getbytes(inputstring); for (int i = 0; i < s.length; i++) { if ((int)s[i] == 63) { templen += 2; } else { templen += 1; } try { tempstring += inputstring.substring(i, 1); } catch { break; } if (templen > len) break; } //如果截过则加上半个省略号 byte[] mybyte = system.text.encoding.default.getbytes(inputstring); if (mybyte.length > len) tempstring += "…"; return tempstring; } #endregion #region 清除html标记 public static string drophtml(string htmlstring) { if (string.isnullorempty(htmlstring)) return ""; //删除脚本 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.replace("<", ""); htmlstring.replace(">", ""); htmlstring.replace("\r\n", ""); htmlstring = httpcontext.current.server.htmlencode(htmlstring).trim(); return htmlstring; } #endregion #region 清除html标记且返回相应的长度 public static string drophtml(string htmlstring, int strlen) { return cutstring(drophtml(htmlstring), strlen); } #endregion #region txt代码转换成html格式 /// <summary> /// 字符串字符处理 /// </summary> /// <param name="chr">等待处理的字符串</param> /// <returns>处理后的字符串</returns> /// //把txt代码转换成html格式 public static string tohtml(string input) { stringbuilder sb = new stringbuilder(input); sb.replace("&", "&"); sb.replace("<", "<"); sb.replace(">", ">"); sb.replace("\r\n", "<br />"); sb.replace("\n", "<br />"); sb.replace("\t", " "); //sb.replace(" ", " "); return sb.tostring(); } #endregion #region html代码转换成txt格式 /// <summary> /// 字符串字符处理 /// </summary> /// <param name="chr">等待处理的字符串</param> /// <returns>处理后的字符串</returns> /// //把html代码转换成txt格式 public static string totxt(string input) { stringbuilder sb = new stringbuilder(input); sb.replace(" ", " "); sb.replace("<br>", "\r\n"); sb.replace("<br>", "\n"); sb.replace("<br />", "\n"); sb.replace("<br />", "\r\n"); sb.replace("<", "<"); sb.replace(">", ">"); sb.replace("&", "&"); return sb.tostring(); } #endregion #region 检测是否有sql危险字符 /// <summary> /// 检测是否有sql危险字符 /// </summary> /// <param name="str">要判断字符串</param> /// <returns>判断结果</returns> public static bool issafesqlstring(string str) { return !regex.ismatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); } /// <summary> /// 检查危险字符 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string filter(string sinput) { if (sinput == null || sinput == "") return null; string sinput1 = sinput.tolower(); string output = sinput; string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'"; if (regex.match(sinput1, regex.escape(pattern), regexoptions.compiled | regexoptions.ignorecase).success) { throw new exception("字符串中含有非法字符!"); } else { output = output.replace("'", "''"); } return output; } /// <summary> /// 检查过滤设定的危险字符 /// </summary> /// <param name="intext">要过滤的字符串 </param> /// <returns>如果参数存在不安全字符,则返回true </returns> public static bool sqlfilter(string word, string intext) { if (intext == null) return false; foreach (string i in word.split('|')) { if ((intext.tolower().indexof(i + " ") > -1) || (intext.tolower().indexof(" " + i) > -1)) { return true; } } return false; } #endregion #region 过滤特殊字符 /// <summary> /// 过滤特殊字符 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string htmls(string input) { if (input != string.empty && input != null) { string ihtml = input.tolower(); ihtml = ihtml.replace("<script", "<script"); ihtml = ihtml.replace("script>", "script>"); ihtml = ihtml.replace("<%", "<%"); ihtml = ihtml.replace("%>", "%>"); ihtml = ihtml.replace("<$", "<$"); ihtml = ihtml.replace("$>", "$>"); return ihtml; } else { return string.empty; } } #endregion #region 检查是否为ip地址 /// <summary> /// 是否为ip /// </summary> /// <param name="ip"></param> /// <returns></returns> public static bool isip(string ip) { 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?)$"); } #endregion #region 获得配置文件节点xml文件的绝对路径 public static string getxmlmappath(string xmlname) { return getmappath(configurationmanager.appsettings[xmlname].tostring()); } #endregion #region 获得当前绝对路径 /// <summary> /// 获得当前绝对路径 /// </summary> /// <param name="strpath">指定的路径</param> /// <returns>绝对路径</returns> public static string getmappath(string strpath) { if (strpath.tolower().startswith("http://")) { return strpath; } if (httpcontext.current != null) { return httpcontext.current.server.mappath(strpath); } else //非web程序引用 { strpath = strpath.replace("/", "\\"); if (strpath.startswith("\\")) { strpath = strpath.substring(strpath.indexof('\\', 1)).trimstart('\\'); } return system.io.path.combine(appdomain.currentdomain.basedirectory, strpath); } } #endregion #region 文件操作 /// <summary> /// 删除单个文件 /// </summary> /// <param name="_filepath">文件相对路径</param> public static bool deletefile(string _filepath) { if (string.isnullorempty(_filepath)) { return false; } string fullpath = getmappath(_filepath); if (file.exists(fullpath)) { file.delete(fullpath); return true; } return false; } /// <summary> /// 删除上传的文件(及缩略图) /// </summary> /// <param name="_filepath"></param> public static void deleteupfile(string _filepath) { if (string.isnullorempty(_filepath)) { return; } string fullpath = getmappath(_filepath); //原图 if (file.exists(fullpath)) { file.delete(fullpath); } if (_filepath.lastindexof("/") >= 0) { string thumbnailpath = _filepath.substring(0, _filepath.lastindexof("/")) + "mall_" + _filepath.substring(_filepath.lastindexof("/") + 1); string fulltpath = getmappath(thumbnailpath); //宿略图 if (file.exists(fulltpath)) { file.delete(fulltpath); } } } /// <summary> /// 删除指定文件夹 /// </summary> /// <param name="_dirpath">文件相对路径</param> public static bool deletedirectory(string _dirpath) { if (string.isnullorempty(_dirpath)) { return false; } string fullpath = getmappath(_dirpath); if (directory.exists(fullpath)) { directory.delete(fullpath, true); return true; } return false; } /// <summary> /// 修改指定文件夹名称 /// </summary> /// <param name="old_dirpath">旧相对路径</param> /// <param name="new_dirpath">新相对路径</param> /// <returns>bool</returns> public static bool movedirectory(string old_dirpath, string new_dirpath) { if (string.isnullorempty(old_dirpath)) { return false; } string fulloldpath = getmappath(old_dirpath); string fullnewpath = getmappath(new_dirpath); if (directory.exists(fulloldpath)) { directory.move(fulloldpath, fullnewpath); return true; } return false; } /// <summary> /// 返回文件大小kb /// </summary> /// <param name="_filepath">文件相对路径</param> /// <returns>int</returns> public static int getfilesize(string _filepath) { if (string.isnullorempty(_filepath)) { return 0; } string fullpath = getmappath(_filepath); if (file.exists(fullpath)) { fileinfo fileinfo = new fileinfo(fullpath); return ((int)fileinfo.length) / 1024; } return 0; } /// <summary> /// 返回文件扩展名,不含“.” /// </summary> /// <param name="_filepath">文件全名称</param> /// <returns>string</returns> public static string getfileext(string _filepath) { if (string.isnullorempty(_filepath)) { return ""; } if (_filepath.lastindexof(".") > 0) { return _filepath.substring(_filepath.lastindexof(".") + 1); //文件扩展名,不含“.” } return ""; } /// <summary> /// 返回文件名,不含路径 /// </summary> /// <param name="_filepath">文件相对路径</param> /// <returns>string</returns> public static string getfilename(string _filepath) { return _filepath.substring(_filepath.lastindexof(@"/") + 1); } /// <summary> /// 文件是否存在 /// </summary> /// <param name="_filepath">文件相对路径</param> /// <returns>bool</returns> public static bool fileexists(string _filepath) { string fullpath = getmappath(_filepath); if (file.exists(fullpath)) { return true; } return false; } #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 = urlencode(strvalue); httpcontext.current.response.appendcookie(cookie); } /// <summary> /// 写cookie值 /// </summary> /// <param name="strname">名称</param> /// <param name="strvalue">值</param> public static void writecookie(string strname, string key, string strvalue) { httpcookie cookie = httpcontext.current.request.cookies[strname]; if (cookie == null) { cookie = new httpcookie(strname); } cookie[key] = urlencode(strvalue); httpcontext.current.response.appendcookie(cookie); } /// <summary> /// 写cookie值 /// </summary> /// <param name="strname">名称</param> /// <param name="strvalue">值</param> public static void writecookie(string strname, string key, string strvalue, int expires) { httpcookie cookie = httpcontext.current.request.cookies[strname]; if (cookie == null) { cookie = new httpcookie(strname); } cookie[key] = urlencode(strvalue); cookie.expires = datetime.now.addminutes(expires); 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 = urlencode(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 urldecode(httpcontext.current.request.cookies[strname].value.tostring()); return ""; } /// <summary> /// 读cookie值 /// </summary> /// <param name="strname">名称</param> /// <returns>cookie值</returns> public static string getcookie(string strname, string key) { if (httpcontext.current.request.cookies != null && httpcontext.current.request.cookies[strname] != null && httpcontext.current.request.cookies[strname][key] != null) return urldecode(httpcontext.current.request.cookies[strname][key].tostring()); return ""; } public static void clearcookie(string strname) { httpcookie cookie = new httpcookie(strname); cookie.values.clear(); cookie.expires = datetime.now.addyears(-1); httpcontext.current.response.appendcookie(cookie); } public static void clearcookie(string strname, string cookiedomain) { httpcookie cookie = new httpcookie(strname); cookie.values.clear(); cookie.expires = datetime.now.addyears(-1); string text = cookiedomain; if (((text != string.empty) && (httpcontext.current.request.url.host.indexof(text) > -1)) && isvaliddomain(httpcontext.current.request.url.host)) { cookie.domain = text; } httpcontext.current.response.appendcookie(cookie); } public static bool isvaliddomain(string host) { regex regex = new regex(@"^\d+$"); if (host.indexof(".") == -1) { return false; } return !regex.ismatch(host.replace(".", string.empty)); } #endregion #region 替换指定的字符串 /// <summary> /// 替换指定的字符串 /// </summary> /// <param name="originalstr">原字符串</param> /// <param name="oldstr">旧字符串</param> /// <param name="newstr">新字符串</param> /// <returns></returns> public static string replacestr(string originalstr, string oldstr, string newstr) { if (string.isnullorempty(oldstr)) { return ""; } return originalstr.replace(oldstr, newstr); } #endregion #region 显示分页 /// <summary> /// 返回分页页码 /// </summary> /// <param name="pagesize">页面大小</param> /// <param name="pageindex">当前页</param> /// <param name="totalcount">总记录数</param> /// <param name="linkurl">链接地址,__id__代表页码</param> /// <param name="centsize">中间页码数量</param> /// <returns></returns> public static string outpagelist(int pagesize, int pageindex, int totalcount, string linkurl, int centsize) { //计算页数 if (totalcount < 1 || pagesize < 1) { return ""; } int pagecount = totalcount / pagesize; if (pagecount < 1) { return ""; } if (totalcount % pagesize > 0) { pagecount += 1; } if (pagecount <= 1) { return ""; } stringbuilder pagestr = new stringbuilder(); string pageid = "__id__"; string firstbtn = "<a href=\"" + replacestr(linkurl, pageid, (pageindex - 1).tostring()) + "\"><</a>"; string lastbtn = "<a href=\"" + replacestr(linkurl, pageid, (pageindex + 1).tostring()) + "\">></a>"; string firststr = "<a href=\"" + replacestr(linkurl, pageid, "1") + "\">1</a>"; string laststr = "<a href=\"" + replacestr(linkurl, pageid, pagecount.tostring()) + "\">" + pagecount.tostring() + "</a>"; if (pageindex <= 1) { firstbtn = "<a href=\"#_\"><</a>"; } if (pageindex >= pagecount) { lastbtn = "<a href=\"#_\">></a>"; } if (pageindex == 1) { firststr = "<a href=\"#_\" class=\"select\">1</a>"; } if (pageindex == pagecount) { laststr = "<a href=\"#_\" class=\"select\">" + pagecount.tostring() + "</a>"; } int firstnum = pageindex - (centsize / 2); //中间开始的页码 if (pageindex < centsize) firstnum = 2; int lastnum = pageindex + centsize - ((centsize / 2) + 1); //中间结束的页码 if (lastnum >= pagecount) lastnum = pagecount - 1; pagestr.append(firstbtn + firststr); if (pageindex >= centsize) { pagestr.append("<span>...</span>\n"); } for (int i = firstnum; i <= lastnum; i++) { if (i == pageindex) { pagestr.append("<a href=\"#_\" class=\"select\">" + i + "</a>"); } else { pagestr.append("<a href=\"" + replacestr(linkurl, pageid, i.tostring()) + "\">" + i + "</a>"); } } if (pagecount - pageindex > centsize - ((centsize / 2))) { pagestr.append("<span>...</span>"); } pagestr.append(laststr + lastbtn); return pagestr.tostring(); } #endregion #region ajax显示分页 /// <summary> /// 返回分页页码 /// </summary> /// <param name="pagesize">页面大小</param> /// <param name="pageindex">当前页</param> /// <param name="totalcount">总记录数</param> /// <param name="linkurl">链接地址,__id__代表页码</param> /// <param name="centsize">中间页码数量</param> /// <returns></returns> public static string outpagelistajax(int pagesize, int pageindex, int totalcount, int centsize) { //计算页数 if (totalcount < 1 || pagesize < 1) { return ""; } int pagecount = totalcount / pagesize; if (pagecount < 1) { return ""; } if (totalcount % pagesize > 0) { pagecount += 1; } if (pagecount <= 1) { return ""; } stringbuilder pagestr = new stringbuilder(); string firstbtn = "<a data-id=\"" + (pageindex - 1).tostring() + "\" href=\"#_\"><</a>"; string lastbtn = "<a data-id=\"" + (pageindex + 1).tostring() + "\" href=\"#_\">></a>"; string firststr = "<a data-id=\"1\" href=\"#_\">1</a>"; string laststr = "<a data-id=\"" + pagecount.tostring() + "\" href=\"#_\">" + pagecount.tostring() + "</a>"; if (pageindex <= 1) { firstbtn = "<a href=\"#_\"><</a>"; } if (pageindex >= pagecount) { lastbtn = "<a href=\"#_\">></a>"; } if (pageindex == 1) { firststr = "<a href=\"#_\" class=\"select\">1</a>"; } if (pageindex == pagecount) { laststr = "<a href=\"#_\" class=\"select\">" + pagecount.tostring() + "</a>"; } int firstnum = pageindex - (centsize / 2); //中间开始的页码 if (pageindex < centsize) firstnum = 2; int lastnum = pageindex + centsize - ((centsize / 2) + 1); //中间结束的页码 if (lastnum >= pagecount) lastnum = pagecount - 1; pagestr.append(firstbtn + firststr); if (pageindex >= centsize) { pagestr.append("<span>...</span>\n"); } for (int i = firstnum; i <= lastnum; i++) { if (i == pageindex) { pagestr.append("<a href=\"#_\" class=\"select\">" + i + "</a>"); } else { pagestr.append("<a data-id=\"" + i.tostring() + "\" href=\"#_\">" + i + "</a>"); } } if (pagecount - pageindex > centsize - ((centsize / 2))) { pagestr.append("<span>...</span>"); } pagestr.append(laststr + lastbtn); return pagestr.tostring(); } #endregion #region url处理 /// <summary> /// url字符编码 /// </summary> public static string urlencode(string str) { if (string.isnullorempty(str)) { return ""; } str = str.replace("'", ""); return httpcontext.current.server.urlencode(str); } /// <summary> /// url字符解码 /// </summary> public static string urldecode(string str) { if (string.isnullorempty(str)) { return ""; } return httpcontext.current.server.urldecode(str); } /// <summary> /// 组合url参数 /// </summary> /// <param name="_url">页面地址</param> /// <param name="_keys">参数名称</param> /// <param name="_values">参数值</param> /// <returns>string</returns> public static string comburltxt(string _url, string _keys, params string[] _values) { stringbuilder urlparams = new stringbuilder(); try { string[] keyarr = _keys.split(new char[] { '&' }); for (int i = 0; i < keyarr.length; i++) { if (!string.isnullorempty(_values[i]) && _values[i] != "0") { _values[i] = urlencode(_values[i]); urlparams.append(string.format(keyarr[i], _values) + "&"); } } if (!string.isnullorempty(urlparams.tostring()) && _url.indexof("?") == -1) urlparams.insert(0, "?"); } catch { return _url; } return _url + dellastchar(urlparams.tostring(), "&"); } #endregion #region url请求数据 /// <summary> /// http post方式请求数据 /// </summary> /// <param name="url">url.</param> /// <param name="param">post的数据</param> /// <returns></returns> public static string httppost(string url, string param) { httpwebrequest request = (httpwebrequest)httpwebrequest.create(url); request.method = "post"; request.contenttype = "application/x-www-form-urlencoded"; request.accept = "*/*"; request.timeout = 15000; request.allowautoredirect = false; streamwriter requeststream = null; webresponse response = null; string responsestr = null; try { requeststream = new streamwriter(request.getrequeststream()); requeststream.write(param); requeststream.close(); response = request.getresponse(); if (response != null) { streamreader reader = new streamreader(response.getresponsestream(), encoding.utf8); responsestr = reader.readtoend(); reader.close(); } } catch (exception) { throw; } finally { request = null; requeststream = null; response = null; } return responsestr; } /// <summary> /// http get方式请求数据. /// </summary> /// <param name="url">url.</param> /// <returns></returns> public static string httpget(string url) { httpwebrequest request = (httpwebrequest)httpwebrequest.create(url); request.method = "get"; //request.contenttype = "application/x-www-form-urlencoded"; request.accept = "*/*"; request.timeout = 15000; request.allowautoredirect = false; webresponse response = null; string responsestr = null; try { response = request.getresponse(); if (response != null) { streamreader reader = new streamreader(response.getresponsestream(), encoding.utf8); responsestr = reader.readtoend(); reader.close(); } } catch (exception) { throw; } finally { request = null; response = null; } return responsestr; } /// <summary> /// 发起get请求,获取响应流 /// </summary> /// <param name="url"></param> /// <returns></returns> public static stream httpgettostream(string url) { try { httpwebrequest req = (httpwebrequest)webrequest.create(url); req.method = "get"; //request.contenttype = "application/x-www-form-urlencoded"; req.accept = "*/*"; using (httpwebresponse response = (httpwebresponse)req.getresponse()) { if (response != null) { return response.getresponsestream(); } return null; } } catch (exception) { return null; } } /// <summary> /// 执行url获取页面内容 /// </summary> public static string urlexecute(string urlpath) { if (string.isnullorempty(urlpath)) { return "error"; } stringwriter sw = new stringwriter(); try { httpcontext.current.server.execute(urlpath, sw); return sw.tostring(); } catch (exception) { return "error"; } finally { sw.close(); sw.dispose(); } } #endregion #region 操作权限菜单 /// <summary> /// 获取操作权限 /// </summary> /// <returns>dictionary</returns> public static dictionary<string, string> actiontype() { dictionary<string, string> dic = new dictionary<string, string>(); dic.add("show", "显示"); dic.add("view", "查看"); dic.add("add", "添加"); dic.add("edit", "修改"); dic.add("delete", "删除"); dic.add("audit", "审核"); dic.add("reply", "回复"); dic.add("confirm", "确认"); dic.add("cancel", "取消"); dic.add("invalid", "作废"); dic.add("build", "生成"); dic.add("instal", "安装"); dic.add("unload", "卸载"); dic.add("back", "备份"); dic.add("restore", "还原"); dic.add("replace", "替换"); return dic; } #endregion #region 替换url /// <summary> /// 替换扩展名 /// </summary> public static string geturlextension(string urlpage, string staticextension) { int indexnum = urlpage.lastindexof('.'); if (indexnum > 0) { return urlpage.replace(urlpage.substring(indexnum), "." + staticextension); } return urlpage; } /// <summary> /// 替换扩展名,如没有扩展名替换默认首页 /// </summary> public static string geturlextension(string urlpage, string staticextension, bool defaultval) { int indexnum = urlpage.lastindexof('.'); if (indexnum > 0) { return urlpage.replace(urlpage.substring(indexnum), "." + staticextension); } if (defaultval) { if (urlpage.endswith("/")) { return urlpage + "index." + staticextension; } else { return urlpage + "/index." + staticextension; } } return urlpage; } #endregion #region 根据ip 获取地名 #region 获取页面ip /// <summary> /// 获得当前页面客户端的ip /// </summary> /// <returns>当前页面客户端的ip</returns> public static string getip() { string result = httpcontext.current.request.servervariables["remote_addr"]; if (string.isnullorempty(result)) result = httpcontext.current.request.servervariables["http_x_forwarded_for"]; if (string.isnullorempty(result)) result = httpcontext.current.request.userhostaddress; if (string.isnullorempty(result) || !utils.isip(result)) return "127.0.0.1"; return result; } #endregion public static string getstringipaddress(string strip)//strip为ip { string urlstring = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=" + getip(); var request = webrequest.create(urlstring) as httpwebrequest; request.method = "get"; request.contenttype = "application/x-www-form-urlencoded; charset=utf-8"; httpwebresponse response = null; try { response = request.getresponse() as httpwebresponse; } catch (webexception ex) { response = ex.response as httpwebresponse; } string result = string.empty; using (streamreader reader = new streamreader(response.getresponsestream(), encoding.default)) { result = reader.readtoend(); string[] sp1 = { "\t" }; string[] temp = result.split(sp1, stringsplitoptions.none); if (temp != null && temp.length >= 6) { return temp[4] + "省" + temp[5] + "市"; } else { return string.empty; } } } #endregion public static bool writetxt(string str) { return writetxt(str, "/debuglog.txt"); } /// <summary> /// 写调试日志 相对路径 /// </summary> /// <param name="str"></param> /// <param name="filepath"></param> /// <returns></returns> public static bool writetxt(string str,string filepath) { try { filestream fs = new filestream(httpcontext.current.request.mappath(filepath==""?"/debuglog.txt":filepath), filemode.append); streamwriter sw = new streamwriter(fs); //开始写入 sw.writeline(str); //清空缓冲区 sw.flush(); //关闭流 sw.close(); fs.close(); } catch (exception) { return false; } return true; } public static string subbetweenstr(string str, string startstr, string endstr) { int sindex = str.indexof(startstr); int eindex = str.lastindexof(endstr); int slength = startstr.length; return str.substring(sindex + slength, eindex - sindex - slength); } /// <summary> /// 根据指定的密码和哈希算法生成一个适合于存储在配置文件中的哈希密码 /// </summary> /// <param name="str">要进行哈希运算的密码</param> /// <param name="type"> 要使用的哈希算法</param> /// <returns>经过哈希运算的密码</returns> public static string hashpasswordforstoringinconfigfile(string str, string type) { return formsauthentication.hashpasswordforstoringinconfigfile(str, type); } public static void responsewrite(string str) { httpcontext.current.response.write(str); httpcontext.current.response.end(); } /// <summary> /// unix时间转换为datetime /// </summary> /// <param name="timestamp"></param> /// <returns></returns> public static datetime unixtimetotime(string timestamp) { datetime dtstart = timezone.currenttimezone.tolocaltime(new datetime(1970, 1, 1)); long ltime = long.parse(timestamp + "0000000"); timespan tonow = new timespan(ltime); return dtstart.add(tonow); } /// <summary> /// datetime转换为unixtime /// </summary> /// <param name="time"></param> /// <returns></returns> public static int convertdatetimeint(system.datetime time) { system.datetime starttime = timezone.currenttimezone.tolocaltime(new system.datetime(1970, 1, 1)); return (int)(time - starttime).totalseconds; } }
jkrequest.cs代码:
/// <summary> /// request操作类 /// </summary> public class jkrequest { /// <summary> /// 判断当前页面是否接收到了post请求 /// </summary> /// <returns>是否接收到了post请求</returns> public static bool ispost() { return httpcontext.current.request.httpmethod.equals("post"); } /// <summary> /// 判断当前页面是否接收到了get请求 /// </summary> /// <returns>是否接收到了get请求</returns> public static bool isget() { return httpcontext.current.request.httpmethod.equals("get"); } /// <summary> /// 返回指定的服务器变量信息 /// </summary> /// <param name="strname">服务器变量名</param> /// <returns>服务器变量信息</returns> public static string getserverstring(string strname) { if (httpcontext.current.request.servervariables[strname] == null) return ""; return httpcontext.current.request.servervariables[strname].tostring(); } /// <summary> /// 返回上一个页面的地址 /// </summary> /// <returns>上一个页面的地址</returns> public static string geturlreferrer() { string retval = null; if (retval == null) return ""; try { retval = httpcontext.current.request.urlreferrer.tostring(); } catch{} return retval; } /// <summary> /// 得到当前完整主机头 /// </summary> /// <returns></returns> public static string getcurrentfullhost() { httprequest request = system.web.httpcontext.current.request; if (!request.url.isdefaultport) return string.format("{0}:{1}", request.url.host, request.url.port.tostring()); return request.url.host; } /// <summary> /// 得到主机头 /// </summary> public static string gethost() { return httpcontext.current.request.url.host; } /// <summary> /// 得到主机名 /// </summary> public static string getdnssafehost() { return httpcontext.current.request.url.dnssafehost; } /// <summary> /// 获取当前请求的原始 url(url 中域信息之后的部分,包括查询字符串(如果存在)) /// </summary> /// <returns>原始 url</returns> public static string getrawurl() { return httpcontext.current.request.rawurl; } /// <summary> /// 判断当前访问是否来自浏览器软件 /// </summary> /// <returns>当前访问是否来自浏览器软件</returns> public static bool isbrowserget() { string[] browsername = {"ie", "opera", "netscape", "mozilla", "konqueror", "firefox"}; string curbrowser = httpcontext.current.request.browser.type.tolower(); for (int i = 0; i < browsername.length; i++) { if (curbrowser.indexof(browsername[i]) >= 0) return true; } return false; } /// <summary> /// 判断是否来自搜索引擎链接 /// </summary> /// <returns>是否来自搜索引擎链接</returns> public static bool issearchenginesget() { if (httpcontext.current.request.urlreferrer == null) return false; string[] searchengine = {"google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou"}; string tmpreferrer = httpcontext.current.request.urlreferrer.tostring().tolower(); for (int i = 0; i < searchengine.length; i++) { if (tmpreferrer.indexof(searchengine[i]) >= 0) return true; } return false; } /// <summary> /// 获得当前完整url地址 /// </summary> /// <returns>当前完整url地址</returns> public static string geturl() { return httpcontext.current.request.url.tostring(); } /// <summary> /// 获得指定url参数的值 /// </summary> /// <param name="strname">url参数</param> /// <returns>url参数的值</returns> public static string getquerystring(string strname) { return getquerystring(strname, false); } public static datetime getquerydatetime(string strname) { return utils.strtodatetime(getquerystring(strname)); } /// <summary> /// 获得指定url参数的值 /// </summary> /// <param name="strname">url参数</param> /// <param name="sqlsafecheck">是否进行sql安全检查</param> /// <returns>url参数的值</returns> public static string getquerystring(string strname, bool sqlsafecheck) { if (httpcontext.current.request.querystring[strname] == null) return ""; if (sqlsafecheck && !utils.issafesqlstring(httpcontext.current.request.querystring[strname])) return "unsafe string"; return httpcontext.current.request.querystring[strname]; } public static int getqueryintvalue(string strname) { return getqueryintvalue(strname, 0); } /// <summary> /// 返回指定url的参数值(int型) /// </summary> /// <param name="strname">url参数</param> /// <param name="defaultvalue">默认值</param> /// <returns>返回指定url的参数值</returns> public static int getqueryintvalue(string strname, int defaultvalue) { if (httpcontext.current.request.querystring[strname] == null || httpcontext.current.request.querystring[strname].tostring() == string.empty) return defaultvalue; else { regex obj = new regex("\\d+"); match objmach = obj.match(httpcontext.current.request.querystring[strname].tostring()); if (objmach.success) return convert.toint32(objmach.value); else return defaultvalue; } } public static string getquerystringvalue(string strname) { return getquerystringvalue(strname, string.empty); } /// <summary> /// 返回指定url的参数值(string型) /// </summary> /// <param name="strname">url参数</param> /// <param name="defaultvalue">默认值</param> /// <returns>返回指定url的参数值</returns> public static string getquerystringvalue(string strname, string defaultvalue) { if (httpcontext.current.request.querystring[strname] == null || httpcontext.current.request.querystring[strname].tostring() == string.empty) return defaultvalue; else { regex obj = new regex("\\w+"); match objmach = obj.match(httpcontext.current.request.querystring[strname].tostring()); if (objmach.success) return objmach.value; else return defaultvalue; } } /// <summary> /// 获得当前页面的名称 /// </summary> /// <returns>当前页面的名称</returns> public static string getpagename() { string [] urlarr = httpcontext.current.request.url.absolutepath.split('/'); return urlarr[urlarr.length - 1].tolower(); } /// <summary> /// 返回表单或url参数的总个数 /// </summary> /// <returns></returns> public static int getparamcount() { return httpcontext.current.request.form.count + httpcontext.current.request.querystring.count; } /// <summary> /// 获得指定表单参数的值 /// </summary> /// <param name="strname">表单参数</param> /// <returns>表单参数的值</returns> public static string getformstring(string strname) { return getformstring(strname, false); } /// <summary> /// 获得指定表单参数的值 /// </summary> /// <param name="strname">表单参数</param> /// <param name="sqlsafecheck">是否进行sql安全检查</param> /// <returns>表单参数的值</returns> public static string getformstring(string strname, bool sqlsafecheck) { if (httpcontext.current.request.form[strname] == null) return ""; if (sqlsafecheck && !utils.issafesqlstring(httpcontext.current.request.form[strname])) return "unsafe string"; return httpcontext.current.request.form[strname]; } /// <summary> /// 返回指定表单的参数值(int型) /// </summary> /// <param name="strname">表单参数</param> /// <returns>返回指定表单的参数值(int型)</returns> public static int getformintvalue(string strname) { return getformintvalue(strname, 0); } /// <summary> /// 返回指定表单的参数值(int型) /// </summary> /// <param name="strname">表单参数</param> /// <param name="defaultvalue">默认值</param> /// <returns>返回指定表单的参数值</returns> public static int getformintvalue(string strname, int defaultvalue) { if (httpcontext.current.request.form[strname] == null || httpcontext.current.request.form[strname].tostring() == string.empty) return defaultvalue; else { regex obj = new regex("\\d+"); match objmach = obj.match(httpcontext.current.request.form[strname].tostring()); if (objmach.success) return convert.toint32(objmach.value); else return defaultvalue; } } /// <summary> /// 返回指定表单的参数值(string型) /// </summary> /// <param name="strname">表单参数</param> /// <returns>返回指定表单的参数值(string型)</returns> public static string getformstringvalue(string strname) { return getquerystringvalue(strname, string.empty); } /// <summary> /// 返回指定表单的参数值(string型) /// </summary> /// <param name="strname">表单参数</param> /// <param name="defaultvalue">默认值</param> /// <returns>返回指定表单的参数值</returns> public static string getformstringvalue(string strname, string defaultvalue) { if (httpcontext.current.request.form[strname] == null || httpcontext.current.request.form[strname].tostring() == string.empty) return defaultvalue; else { regex obj = new regex("\\w+"); match objmach = obj.match(httpcontext.current.request.form[strname].tostring()); if (objmach.success) return objmach.value; else return defaultvalue; } } /// <summary> /// 获得url或表单参数的值, 先判断url参数是否为空字符串, 如为true则返回表单参数的值 /// </summary> /// <param name="strname">参数</param> /// <returns>url或表单参数的值</returns> public static string getstring(string strname) { return getstring(strname, false); } /// <summary> /// 获得url或表单参数的值, 先判断url参数是否为空字符串, 如为true则返回表单参数的值 /// </summary> /// <param name="strname">参数</param> /// <param name="sqlsafecheck">是否进行sql安全检查</param> /// <returns>url或表单参数的值</returns> public static string getstring(string strname, bool sqlsafecheck) { if ("".equals(getquerystring(strname))) return getformstring(strname, sqlsafecheck); else return getquerystring(strname, sqlsafecheck); } public static string getstringvalue(string strname) { return getstringvalue(strname, string.empty); } /// <summary> /// 获得url或表单参数的值, 先判断url参数是否为空字符串, 如为true则返回表单参数的值 /// </summary> /// <param name="strname">参数</param> /// <param name="sqlsafecheck">是否进行sql安全检查</param> /// <returns>url或表单参数的值</returns> public static string getstringvalue(string strname, string defaultvalue) { if ("".equals(getquerystringvalue(strname))) return getformstringvalue(strname, defaultvalue); else return getquerystringvalue(strname, defaultvalue); } /// <summary> /// 获得指定url参数的int类型值 /// </summary> /// <param name="strname">url参数</param> /// <returns>url参数的int类型值</returns> public static int getqueryint(string strname) { return utils.strtoint(httpcontext.current.request.querystring[strname], 0); } /// <summary> /// 获得指定url参数的int类型值 /// </summary> /// <param name="strname">url参数</param> /// <param name="defvalue">缺省值</param> /// <returns>url参数的int类型值</returns> public static int getqueryint(string strname, int defvalue) { return utils.strtoint(httpcontext.current.request.querystring[strname], defvalue); } /// <summary> /// 获得指定表单参数的int类型值 /// </summary> /// <param name="strname">表单参数</param> /// <returns>表单参数的int类型值</returns> public static int getformint(string strname) { return getformint(strname, 0); } /// <summary> /// 获得指定表单参数的int类型值 /// </summary> /// <param name="strname">表单参数</param> /// <param name="defvalue">缺省值</param> /// <returns>表单参数的int类型值</returns> public static int getformint(string strname, int defvalue) { return utils.strtoint(httpcontext.current.request.form[strname], defvalue); } /// <summary> /// 获得指定url或表单参数的int类型值, 先判断url参数是否为缺省值, 如为true则返回表单参数的值 /// </summary> /// <param name="strname">url或表单参数</param> /// <param name="defvalue">缺省值</param> /// <returns>url或表单参数的int类型值</returns> public static int getint(string strname, int defvalue) { if (getqueryint(strname, defvalue) == defvalue) return getformint(strname, defvalue); else return getqueryint(strname, defvalue); } /// <summary> /// 获得指定url参数的decimal类型值 /// </summary> /// <param name="strname">url参数</param> /// <param name="defvalue">缺省值</param> /// <returns>url参数的decimal类型值</returns> public static decimal getquerydecimal(string strname, decimal defvalue) { return utils.strtodecimal(httpcontext.current.request.querystring[strname], defvalue); } /// <summary> /// 获得指定表单参数的decimal类型值 /// </summary> /// <param name="strname">表单参数</param> /// <param name="defvalue">缺省值</param> /// <returns>表单参数的decimal类型值</returns> public static decimal getformdecimal(string strname, decimal defvalue) { return utils.strtodecimal(httpcontext.current.request.form[strname], defvalue); } /// <summary> /// 获得指定url参数的float类型值 /// </summary> /// <param name="strname">url参数</param> /// <param name="defvalue">缺省值</param> /// <returns>url参数的int类型值</returns> public static float getqueryfloat(string strname, float defvalue) { return utils.strtofloat(httpcontext.current.request.querystring[strname], defvalue); } /// <summary> /// 获得指定表单参数的float类型值 /// </summary> /// <param name="strname">表单参数</param> /// <param name="defvalue">缺省值</param> /// <returns>表单参数的float类型值</returns> public static float getformfloat(string strname, float defvalue) { return utils.strtofloat(httpcontext.current.request.form[strname], defvalue); } /// <summary> /// 获得指定url或表单参数的float类型值, 先判断url参数是否为缺省值, 如为true则返回表单参数的值 /// </summary> /// <param name="strname">url或表单参数</param> /// <param name="defvalue">缺省值</param> /// <returns>url或表单参数的int类型值</returns> public static float getfloat(string strname, float defvalue) { if (getqueryfloat(strname, defvalue) == defvalue) return getformfloat(strname, defvalue); else return getqueryfloat(strname, defvalue); } /// <summary> /// 获得当前页面客户端的ip /// </summary> /// <returns>当前页面客户端的ip</returns> public static string getip() { string result = httpcontext.current.request.servervariables["remote_addr"]; if (string.isnullorempty(result)) result = httpcontext.current.request.servervariables["http_x_forwarded_for"]; if (string.isnullorempty(result)) result = httpcontext.current.request.userhostaddress; if (string.isnullorempty(result) || !utils.isip(result)) return "127.0.0.1"; return result; } public static stream getinputstream() { return system.web.httpcontext.current.request.inputstream; } }
wxpayhelper类库下的utils类:
namespace wxpayhelper { public class utils { public static string getunifyurlxml<t>(t t,string key,out string url,out string _sign) { type type = typeof (t); dictionary<string,string> dic = new dictionary<string, string>(); propertyinfo[] pis = type.getproperties(); #region 组合url参数到字典里 foreach (propertyinfo pi in pis) { object val = pi.getvalue(t, null); if (val != null) { dic.add(pi.name, val.tostring()); } } #endregion //字典排序 var dictemp = dic.orderby(d => d.key); #region 生成url字符串 stringbuilder str = new stringbuilder(); foreach (var item in dictemp) { str.appendformat("{0}={1}&", item.key, item.value); } #endregion var ourl= str.tostring().trim('&'); //加上key string tempsign = ourl + "&key="+key; //md5加密后,转换成大写 string sign = md5(tempsign).toupper(); //将签名添加到字典中 dic.add("sign", sign); _sign = sign; url = str.appendformat("sign={0}",sign).tostring(); loghelper.writefile(url); //生成请求的内容,并返回 return parserequestxml(dic); } public static string getunifyrequestxml<t>(t t, string key, out string url, out string _sign) { type type = typeof(t); dictionary<string, string> dic = new dictionary<string, string>(); propertyinfo[] pis = type.getproperties(); #region 组合url参数到字典里 foreach (propertyinfo pi in pis) { object val = pi.getvalue(t, null); if (val != null) { dic.add(pi.name, val.tostring()); } } #endregion //字典排序 var dictemp = dic.orderby(d => d.key); #region 生成url字符串 stringbuilder str = new stringbuilder(); foreach (var item in dictemp) { str.appendformat("{0}={1}&", item.key, item.value); } #endregion var ourl = str.tostring().trim('&'); //加上key string tempsign = ourl + "&key=" + key; //md5加密后,转换成大写 string sign = md5(tempsign).toupper(); //将签名添加到字典中 dic.add("sign", sign); _sign = sign; url = str.appendformat("sign={0}", sign).tostring(); loghelper.writefile(url); //生成请求的内容,并返回 return parserequestxml(dic); } public static string parserequestxml(dictionary<string, string> parameters) { stringbuilder sb = new stringbuilder(); sb.append("<xml>"); foreach (keyvaluepair<string, string> k in parameters) { if (k.key == "detail") { sb.append("<" + k.key + "><![cdata[" + k.value + "]]></" + k.key + ">"); } else { sb.append("<" + k.key + ">" + k.value + "</" + k.key + ">"); } } sb.append("</xml>"); loghelper.writefile(sb.tostring()); return sb.tostring(); } public static string parsexml(dictionary<string, string> parameters) { stringbuilder sb = new stringbuilder(); sb.append("<xml>"); foreach (string k in parameters.keys) { string v = (string)parameters[k]; if (regex.ismatch(v, @"^[0-9.]$")) { sb.append("<" + k + ">" + v + "</" + k + ">"); } else { sb.append("<" + k + "><![cdata[" + v + "]]></" + k + ">"); } } //foreach (keyvaluepair<string, string> k in parameters) //{ // if (k.key == "detail") // { // sb.append("<" + k.key + "><![cdata[" + k.value + "]]></" + k.key + ">"); // } // else // { // sb.append("<" + k.key + ">" + k.value + "</" + k.key + ">"); // } //} sb.append("</xml>"); loghelper.writefile(sb.tostring()); return sb.tostring(); } /// <summary> /// 获取32位随机数(guid) /// </summary> /// <returns></returns> public static string getrandom() { return guid.newguid().tostring("n"); } /// <summary> /// 获取微信版本 /// </summary> /// <param name="ua"></param> /// <returns></returns> public static string getweixinversion(string ua) { int last = ua.lastindexof("micromessenger"); string[] wxversion = ua.remove(0, last).split(' '); return wxversion[0].split('/')[1].substring(0, 3); } #region md5加密 public static string md5(string pwd) { md5 md5 = new md5cryptoserviceprovider(); byte[] data = system.text.encoding.utf8.getbytes(pwd); byte[] md5data = md5.computehash(data); md5.clear(); string str = ""; for (int i = 0; i < md5data.length; i++) { str += md5data[i].tostring("x").padleft(2, '0'); } return str; } #endregion public static string httppost(string url, string param) { httpwebrequest request = (httpwebrequest)httpwebrequest.create(url); request.method = "post"; request.contenttype = "application/x-www-form-urlencoded"; request.accept = "*/*"; request.timeout = 15000; request.allowautoredirect = false; streamwriter requeststream = null; webresponse response = null; string responsestr = null; try { requeststream = new streamwriter(request.getrequeststream()); requeststream.write(param); requeststream.close(); response = request.getresponse(); if (response != null) { streamreader reader = new streamreader(response.getresponsestream(), encoding.utf8); responsestr = reader.readtoend(); reader.close(); } } catch (exception) { throw; } finally { request = null; requeststream = null; response = null; } return responsestr; } /// <summary> /// datetime转换为unixtime /// </summary> /// <param name="time"></param> /// <returns></returns> public static int convertdatetimeint(system.datetime time) { system.datetime starttime = timezone.currenttimezone.tolocaltime(new system.datetime(1970, 1, 1)); return (int)(time - starttime).totalseconds; } public static bool writetxt(string str) { try { filestream fs = new filestream(httpcontext.current.request.mappath("/buglog.txt"), filemode.append); streamwriter sw = new streamwriter(fs); //开始写入 sw.writeline(str); //清空缓冲区 sw.flush(); //关闭流 sw.close(); fs.close(); } catch (exception) { return false; } return true; } /// <summary> /// 生成二维码流 /// </summary> /// <param name="qrcontent"></param> /// <returns></returns> public static memorystream getqrcodestream(string qrcontent) { //误差校正水平 errorcorrectionlevel eclevel = errorcorrectionlevel.m; //空白区域 quietzonemodules quietzone = quietzonemodules.zero; int modulesize = 120;//大小 qrcode qrcode; var encoder = new qrencoder(eclevel); //对内容进行编码,并保存生成的矩阵 if (encoder.tryencode(qrcontent,out qrcode)) { var render = new graphicsrenderer(new fixedcodesize(modulesize, quietzone)); memorystream stream = new memorystream(); render.writetostream(qrcode.matrix, imageformat.jpeg,stream); return stream; } return null; } public static void getqrcode(string qrcontent) { memorystream ms = getqrcodestream(qrcontent); httpcontext.current.response.clearcontent(); httpcontext.current.response.contenttype = "image/png"; httpcontext.current.response.binarywrite(ms.toarray()); } } }
本文已被整理到了《asp.net微信开发教程汇总》,欢迎大家学习阅读。
为大家推荐现在关注度比较高的微信小程序教程一篇:《微信小程序开发教程》小编为大家精心整理的,希望喜欢。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。