1
yhj
2024-07-24 5e5d945e91568b973faa27d8ab0bcef99fc4a6c5
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
#region
 
using System;
using System.Configuration;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Text;
using CSFrameworkV5.Core.Common;
 
#endregion
 
namespace CSFrameworkV5.WebRef
{
    /// <summary>
    ///     统一构建WCF通信对象实例
    /// </summary>
    public static class WCFFactory
    {
        /// <summary>
        ///     创建BasicHttpBinding协议绑定
        /// </summary>
        /// <param name="ws"></param>
        public static BasicHttpBinding CreateBasicHttpBinding(
            bool https = false)
        {
            var ws = new BasicHttpBinding();
 
            ws.Name = "BasicHttpBinding";
            ws.MaxReceivedMessageSize = 2147483647; //最大接收的消息大小 
            ws.MaxBufferSize = 2147483647; // 从通道接收消息的缓存大小 
            ws.MaxBufferPoolSize = 2147483647; //从通道接收消息的最大缓存数量 
            ws.CloseTimeout = new TimeSpan(0, 10, 0);
            ws.OpenTimeout = new TimeSpan(0, 10, 0);
            ws.SendTimeout = new TimeSpan(0, 10, 0);
            ws.ReceiveTimeout = new TimeSpan(0, 10, 0);
 
            ws.AllowCookies = false;
            ws.BypassProxyOnLocal = false;
            ws.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            ws.MessageEncoding = WSMessageEncoding.Text;
            ws.TextEncoding = Encoding.UTF8;
            ws.TransferMode = TransferMode.Buffered;
            ws.UseDefaultWebProxy = true;
 
            //security节点配置 - HTTPS 协议配置
            if (https)
            {
                ws.Security.Mode = BasicHttpSecurityMode.Transport;
                ws.Security.Transport.ClientCredentialType =
                    HttpClientCredentialType.None;
                ws.Security.Transport.ProxyCredentialType =
                    HttpProxyCredentialType.None;
                ws.Security.Transport.Realm = "";
            }
            else
            {
                //security节点配置 - HTTP协议配置
                ws.Security.Mode = BasicHttpSecurityMode.None;
                ws.Security.Transport.ClientCredentialType =
                    HttpClientCredentialType.None;
                ws.Security.Transport.ProxyCredentialType =
                    HttpProxyCredentialType.None;
                ws.Security.Transport.Realm = "";
            }
 
            var rq = ws.ReaderQuotas;
            rq.MaxArrayLength = 2147483647; //最大数组长度 
            rq.MaxBytesPerRead = 6553600; //最大每次读取长度 
            rq.MaxDepth = 6553600; // 最大节点深度 
            rq.MaxNameTableCharCount = 6553600; //最大NameTableChar的数量 
            rq.MaxStringContentLength = 2147483647; // 最大内容长度             
 
            return ws;
        }
 
        /// <summary>
        ///     创建NetTcpBinding协议绑定
        /// </summary>
        /// <param name="https"></param>
        /// <returns></returns>
        public static NetTcpBinding CreateNetTcpBinding(bool https = false)
        {
            var ws = new NetTcpBinding();
 
            ws.Name = "NetTcpBinding";
 
            ws.MaxReceivedMessageSize = 2147483647; //最大接收的消息大小 
            ws.MaxBufferSize = 2147483647; // 从通道接收消息的缓存大小 
            ws.MaxBufferPoolSize = 2147483647; //从通道接收消息的最大缓存数量 
 
            ws.CloseTimeout = new TimeSpan(0, 10, 0);
            ws.OpenTimeout = new TimeSpan(0, 10, 0);
            ws.SendTimeout = new TimeSpan(0, 10, 0);
            ws.ReceiveTimeout = new TimeSpan(0, 10, 0);
 
            ws.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            ws.PortSharingEnabled =
                false; //获取或设置一个值,该值指示是否为采用此绑定配置的连接启用 TCP 端口共享。
 
            //ws.MaxConnections = 256;//如果修改maxConnections的值,服务会导致不正常,会报端口已经被占用
            //ws.ListenBacklog = 10; 
 
            ws.TransferMode = TransferMode.Buffered;
            ws.TransactionProtocol = TransactionProtocol.OleTransactions;
            ws.TransactionFlow = false;
 
            ws.ReliableSession.Ordered = true;
            ws.ReliableSession.InactivityTimeout = new TimeSpan(0, 10, 0);
 
            //security节点配置 - HTTPS 协议配置
            if (https)
            {
                ws.Security.Mode = SecurityMode.Transport;
                ws.Security.Transport.ClientCredentialType =
                    TcpClientCredentialType.None;
                ws.Security.Transport.ProtectionLevel = ProtectionLevel.None;
            }
            else
            {
                //security节点配置 - HTTP协议配置
                ws.Security.Mode = SecurityMode.None;
                ws.Security.Transport.ClientCredentialType =
                    TcpClientCredentialType.None;
                ws.Security.Transport.ProtectionLevel = ProtectionLevel.None;
            }
 
            var rq = ws.ReaderQuotas;
            rq.MaxArrayLength = 2147483647; //最大数组长度 
            rq.MaxBytesPerRead = 6553600; //最大每次读取长度 
            rq.MaxDepth = 6553600; // 最大节点深度 
            rq.MaxNameTableCharCount = 6553600; //最大NameTableChar的数量 
            rq.MaxStringContentLength = 2147483647; // 最大内容长度 
 
            return ws;
        }
 
        /// <summary>
        ///     设置WSHttpBinding参数配置
        /// </summary>
        /// <param name="ws"></param>
        public static WSHttpBinding CreateWSHttpBinding(bool https = false)
        {
            var ws = new WSHttpBinding();
 
            ws.Name = "wsHttpBinding";
            ws.CloseTimeout = new TimeSpan(0, 10, 0);
            ws.OpenTimeout = new TimeSpan(0, 10, 0);
            ws.ReceiveTimeout = new TimeSpan(0, 10, 0);
            ws.SendTimeout = new TimeSpan(0, 10, 0);
 
            ws.MaxBufferPoolSize = 2147483647; //从通道接收消息的最大缓存数量 
            ws.MaxReceivedMessageSize = 2147483647; //最大接收的消息大小             
 
            ws.BypassProxyOnLocal = false;
            ws.TransactionFlow = false;
            ws.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
 
            ws.MessageEncoding = WSMessageEncoding.Text;
            ws.TextEncoding = Encoding.UTF8;
            ws.UseDefaultWebProxy = true;
            ws.AllowCookies = false;
 
            //readerQuotas节点配置
            var rq = ws.ReaderQuotas;
            rq.MaxArrayLength = 2147483647; //最大数组长度 
            rq.MaxBytesPerRead = 6553600; //最大每次读取长度 
            rq.MaxDepth = 6553600; // 最大节点深度 
            rq.MaxNameTableCharCount = 6553600; //最大NameTableChar的数量 
            rq.MaxStringContentLength = 2147483647; // 最大内容长度 
 
            //reliableSession节点配置
            ws.ReliableSession.Enabled = false;
            ws.ReliableSession.Ordered = true;
            ws.ReliableSession.InactivityTimeout = new TimeSpan(0, 10, 0);
 
            //security节点配置 - HTTPS 协议配置
            if (https)
            {
                ws.Security.Mode = SecurityMode.Transport;
                ws.Security.Transport.ClientCredentialType =
                    HttpClientCredentialType.None;
                ws.Security.Transport.ProxyCredentialType =
                    HttpProxyCredentialType.None;
            }
            else
            {
                //security节点配置 - HTTP协议配置
                ws.Security.Mode = SecurityMode.None;
                ws.Security.Transport.ClientCredentialType =
                    HttpClientCredentialType.None;
                ws.Security.Transport.ProxyCredentialType =
                    HttpProxyCredentialType.None;
            }
 
            ws.Security.Message.ClientCredentialType =
                MessageCredentialType.None;
            ws.Security.Message.EstablishSecurityContext = false;
            ws.Security.Message.NegotiateServiceCredential = false;
 
            return ws;
        }
 
        private static string GetPassword()
        {
            var pwd = ConfigurationManager.AppSettings["Windows_Password"];
            return KeyProvider.Default.Decrypt(pwd);
        }
 
        private static string GetSSLPassword()
        {
            var pwd = ConfigurationManager.AppSettings["SSLPassword"];
            return KeyProvider.Default.Decrypt(pwd);
        }
 
        private static string GetUserName()
        {
            var name = ConfigurationManager.AppSettings["Windows_UserName"];
            return KeyProvider.Default.Decrypt(name);
        }
 
        #region Create方法
 
        /// <summary>
        ///     动态创建WCF接口透明代理
        /// </summary>
        /// <typeparam name="T">WCF接口,如:ICommonService</typeparam>
        /// <param name="uri">连接地址</param>
        /// <returns></returns>
        public static T Create<T>(string uri = "") where T : class
        {
            //获取WCF接口的名称,如:ICommonService
            var iName = typeof(T).Name;
 
            //获取接口的URI地址,必须是主程序的App.config配置文件
            if (string.IsNullOrWhiteSpace(uri))
                uri = ConfigurationManager.AppSettings[iName];
 
            //支持4种凭据类型:None/ Basic / Windows / Certificate            
            var UseCredentials =
                ConfigurationManager.AppSettings["UseCredentials"];
 
            //default:None
            switch (UseCredentials)
            {
                case "Basic":
                    return CreateBasic<T>(uri); //Basic认证,需要指定Windows用户/密码
                case "Windows":
                    return CreateWindows<T>(uri); //Windows认证,需要指定Windows用户/密码
                case "Certificate":
                    return
                        CreateCertificate<T>(uri); //Certificate认证,需要提供SSL证书文件
                default: return CreateNone<T>(uri);
            }
 
            //是否使用https协议,默认false
            //bool https = System.Configuration.ConfigurationManager.AppSettings["UseHttps"].ToLower() == "true";
 
            //C#动态创建WCF协议配置实例(不依赖App.config配置文件)
            //var myBinding = CreateWSHttpBinding(https);
 
            //获取协议配置并创建实例,必须是主程序的App.config配置文件            
            //var myBinding = new WSHttpBinding("WSHttpBinding");
            //var myBinding = new BasicHttpBinding("BasicHttpBinding");
            //var myBinding = new NetTcpBinding("NetTcpBinding");
        }
 
        /// <summary>
        ///     动态创建WCF接口透明代理 - 无认证模式(None)
        /// </summary>
        /// <typeparam name="T">WCF接口,如:ICommonService</typeparam>
        /// <param name="uri">连接地址</param>
        /// <returns></returns>
        public static T CreateNone<T>(string uri = "") where T : class
        {
            //获取协议配置并创建实例,必须是主程序的App.config配置文件            
            var myBinding = new WSHttpBinding("WSHttpBinding");
            var myEndpoint = new EndpointAddress(new Uri(uri));
            var myChannelFactory = new ChannelFactory<T>(myBinding, myEndpoint);
 
            //创建WCF通道
            var instance = myChannelFactory.CreateChannel();
 
            return instance;
        }
 
        /// <summary>
        ///     动态创建WCF接口透明代理 - BASIC认证
        /// </summary>
        /// <typeparam name="T">WCF接口,如:ICommonService</typeparam>
        /// <param name="uri">连接地址</param>
        /// <returns></returns>
        public static T CreateBasic<T>(string uri = "") where T : class
        {
            //获取协议配置并创建实例,必须是主程序的App.config配置文件            
            var myBinding = new WSHttpBinding("WSHttpBinding");
            var myEndpoint = new EndpointAddress(new Uri(uri));
            var myChannelFactory = new ChannelFactory<T>(myBinding, myEndpoint);
 
            //重要!!!设置BASIC认证-需要的本地Windows认证的用户名及密码
            myChannelFactory.Credentials.UserName.UserName = GetUserName();
            myChannelFactory.Credentials.UserName.Password = GetPassword();
 
            //创建WCF通道
            var instance = myChannelFactory.CreateChannel();
 
            return instance;
        }
 
        /// <summary>
        ///     动态创建WCF接口透明代理 - Windows身份认证
        /// </summary>
        /// <typeparam name="T">WCF接口,如:ICommonService</typeparam>
        /// <param name="uri">连接地址</param>
        /// <returns></returns>
        public static T CreateWindows<T>(string uri = "") where T : class
        {
            //获取协议配置并创建实例,必须是主程序的App.config配置文件            
            var myBinding = new WSHttpBinding("WSHttpBinding");
            var myEndpoint = new EndpointAddress(new Uri(uri));
            var myChannelFactory = new ChannelFactory<T>(myBinding, myEndpoint);
 
            //重要!!!Windows身份认证-需要的本地Windows认证的用户名及密码            
            var identity = new NetworkCredential(GetUserName(), GetPassword());
 
            //Windows身份认证信息
            myChannelFactory.Credentials.Windows.ClientCredential = identity;
 
            //创建WCF通道
            var instance = myChannelFactory.CreateChannel();
 
            return instance;
        }
 
        /// <summary>
        ///     动态创建WCF接口透明代理 - Certificate证书认证
        /// </summary>
        /// <typeparam name="T">WCF接口,如:ICommonService</typeparam>
        /// <param name="uri">连接地址</param>
        /// <returns></returns>
        public static T CreateCertificate<T>(string uri = "") where T : class
        {
            //获取协议配置并创建实例,必须是主程序的App.config配置文件            
            var myBinding = new WSHttpBinding("WSHttpBinding");
            var myEndpoint = new EndpointAddress(new Uri(uri));
            var myChannelFactory = new ChannelFactory<T>(myBinding, myEndpoint);
 
            //ssl证书文件及密码
            var pfxPath =
                @"C:\Users\Administrator\Downloads\5914048_cs5.manonwo.com.pfx";
            var pfxPwd = GetSSLPassword();
 
            //设置客户端证书文件
            var clientCer = new X509Certificate2(pfxPath, pfxPwd,
                X509KeyStorageFlags.MachineKeySet);
            myChannelFactory.Credentials.ClientCertificate.Certificate =
                clientCer;
 
            //创建WCF通道
            var instance = myChannelFactory.CreateChannel();
            return instance;
        }
 
        #endregion
    }
}