最近在一个项目中有所使用,记录下来便于以后查阅。
WCF操作类,使用于客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Reflection;
namespace YS.Common
{
/// <summary>
/// 使用ChannelFactory为wcf客户端创建独立通道
/// </summary>
public class WcfChannelFactory
{
public WcfChannelFactory()
{
}
/// <summary>
/// 执行方法 WSHttpBinding
/// </summary>
/// <typeparam name="T">服务接口</typeparam>
/// <param name="uri">wcf地址</param>
/// <param name="methodName">方法名</param>
/// <param name="args">参数列表</param>
public static object ExecuteMetod<T>(string uri, string methodName, params object[] args)
{
BasicHttpBinding binding = new BasicHttpBinding(); //出现异常:远程服务器返回错误: (415) Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'.。
//WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress(uri);
using (ChannelFactory<T> channelFactory = new ChannelFactory<T>(binding, endpoint))
{
T instance = channelFactory.CreateChannel();
using (instance as IDisposable)
{
try
{
Type type = typeof(T);
MethodInfo mi = type.GetMethod(methodName);
return mi.Invoke(instance, args);
}
catch (TimeoutException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (CommunicationException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (Exception vErr)
{
(instance as ICommunicationObject).Abort();
throw;
}
}
}
}
//nettcpbinding 绑定方式
public static object ExecuteMethod<T>(string pUrl, string pMethodName, params object[] pParams)
{
EndpointAddress address = new EndpointAddress(pUrl);
Binding bindinginstance = null;
NetTcpBinding ws = new NetTcpBinding();
ws.MaxReceivedMessageSize = 20971520;
ws.Security.Mode = SecurityMode.None;
bindinginstance = ws;
using (ChannelFactory<T> channel = new ChannelFactory<T>(bindinginstance, address))
{
T instance = channel.CreateChannel();
using (instance as IDisposable)
{
try
{
Type type = typeof(T);
MethodInfo mi = type.GetMethod(pMethodName);
return mi.Invoke(instance, pParams);
}
catch (TimeoutException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (CommunicationException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (Exception vErr)
{
(instance as ICommunicationObject).Abort();
throw;
}
}
}
}
}
}
客户端建立对应接口,例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Reflection;
using System.Data;
using CYQ.Data;
using CYQ.Data.Table;
namespace YS.Web
{
[ServiceContract]
public interface Iapi
{
[OperationContract]
void DoWork();
[OperationContract]
string test();
[OperationContract]
decimal get_kucun(string code);
[OperationContract]
DataTable get_table_list(string table_name, string _strWhere);
[OperationContract]
DataTable get_table_list(string table_name, int page, int pageSize, string _strWhere, out int totalCount);
}
}
客户端使用
string uri = "http://127.0.0.1:85/wcf/api.svc";
object o =Common.WcfChannelFactory.ExecuteMetod<Iapi>(uri, "test");
Response.Write(o);
服务端采用正常WCF架构即可
另外一种方法
public class WcfInvokeFactory
{
#region WCF服务工厂
public static T CreateServiceByUrl<T>(string url)
{
return CreateServiceByUrl<T>(url, "basicHttpBinding");
}
public static T CreateServiceByUrl<T>(string url, string bing)
{
try
{
if (string.IsNullOrEmpty(url)) throw new NotSupportedException("This url is not Null or Empty!");
EndpointAddress address = new EndpointAddress(url);
Binding binding = CreateBinding(bing);
ChannelFactory<T> factory = new ChannelFactory<T>(binding, address);
return factory.CreateChannel();
}
catch (Exception ex)
{
throw new Exception("创建服务工厂出现异常.");
}
}
#endregion
#region 创建传输协议
/// <summary>
/// 创建传输协议
/// </summary>
/// <param name="binding">传输协议名称</param>
/// <returns></returns>
private static Binding CreateBinding(string binding)
{
Binding bindinginstance = null;
if (binding.ToLower() == "basichttpbinding")
{
BasicHttpBinding ws = new BasicHttpBinding();
ws.MaxBufferSize = 2147483647;
ws.MaxBufferPoolSize = 2147483647;
ws.MaxReceivedMessageSize = 2147483647;
ws.ReaderQuotas.MaxStringContentLength = 2147483647;
ws.CloseTimeout = new TimeSpan(0, 30, 0);
ws.OpenTimeout = new TimeSpan(0, 30, 0);
ws.ReceiveTimeout = new TimeSpan(0, 30, 0);
ws.SendTimeout = new TimeSpan(0, 30, 0);
bindinginstance = ws;
}
else if (binding.ToLower() == "nettcpbinding")
{
NetTcpBinding ws = new NetTcpBinding();
ws.MaxReceivedMessageSize = 65535000;
ws.Security.Mode = SecurityMode.None;
bindinginstance = ws;
}
else if (binding.ToLower() == "wshttpbinding")
{
WSHttpBinding ws = new WSHttpBinding(SecurityMode.None);
ws.MaxReceivedMessageSize = 65535000;
ws.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.Windows;
ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
bindinginstance = ws;
}
return bindinginstance;
}
#endregion
}
调用
Iapi proxy = WcfInvokeFactory.CreateServiceByUrl<Iapi>(dr1["url"] + "/wcf/api.svc");
DataTable result = proxy.get_table_list(tablename, "1=1");