本文实例为大家分享了微信JS SDK支付的具体代码,供大家参考,具体内容如下
模型层实体类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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 ; }
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
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 ; }
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
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内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<%@ 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代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
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代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
/// <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代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
|
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代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
|
/// <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类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
|
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());
}
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。