.net core 下調用.nett framework框架的WCF方法寫法
阿新 • • 發佈:2018-05-17
連接 allow ram tom face rtb ade 類繼承 form
通過添加服務引用後生成的代碼,可以得知首先要設置Basic連接寫法的屬性,並且設置WCF服務的地址:
我在這裏建立工廠類如下:
using System; using System.ServiceModel; using System.ServiceModel.Channels; using ShoppingMall.Enums; namespace ShoppingMall.ClientBll { public class EndpointFactory { private static Binding GetBindingForEndpoint(EndpointConfigurationEnums endpointConfiguration) {if ((endpointConfiguration == EndpointConfigurationEnums.BasicHttpBinding_ICustomerService)) { BasicHttpBinding result = new BasicHttpBinding(); result.MaxBufferSize = int.MaxValue; result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; result.MaxReceivedMessageSize= int.MaxValue; result.AllowCookies = true; return result; } throw new InvalidOperationException(string.Format("找不到名稱為“{0}”的終結點。", endpointConfiguration)); } private static EndpointAddress GetEndpointAddress(EndpointConfigurationEnums endpointConfiguration) {if ((endpointConfiguration == EndpointConfigurationEnums.BasicHttpBinding_ICustomerService)) { return new EndpointAddress("http://你的地址"); } throw new InvalidOperationException(string.Format("找不到名稱為“{0}”的終結點。", endpointConfiguration)); } public static Binding GetDefaultBinding() { return GetBindingForEndpoint(EndpointConfigurationEnums.BasicHttpBinding_ICustomerService); } public static EndpointAddress GetDefaultEndpointAddress() { return GetEndpointAddress(EndpointConfigurationEnums.BasicHttpBinding_ICustomerService); } } }
然後,在客戶端調用時需要調用類繼承ClientBase類並且繼承WCF的接口,該類的類型是服WCF接口的類型
並且要再客戶端調用類的構造參數中繼承ClientBase的構造方法,實例化Basic以及WCF服務的地址
最後通過繼承ClientBase的Channel方式調用服務方法,完全代碼如下:
using Microsoft.Extensions.Configuration; using ShoppingMall.IService; using ShoppingMall.Model; using System.Collections.Generic; using System.ServiceModel; namespace ShoppingMall.ClientBll { public class CustomerBll:ClientBase<ICustomerService>, ICustomerService { public IConfigurationRoot configuration; public CustomerBll() : base(EndpointFactory.GetDefaultBinding(), EndpointFactory.GetDefaultEndpointAddress()) { } public List<Buyer> GetBuyerList() { return Channel.GetBuyerList(); } public bool InsertBuyerInfo(Buyer info) { return Channel.InsertBuyerInfo(info); } } }
其次,WCF的服務接口應該有對應標記,例如:
using ShoppingMall.Model; using System.Collections.Generic; using System.ServiceModel; namespace ShoppingMall.IService { /// <summary> /// 用戶信息處理服務 /// </summary> [ServiceContract] public interface ICustomerService { /// <summary> /// 獲取買家列表 /// </summary> /// <returns></returns> [OperationContract] List<Buyer> GetBuyerList(); /// <summary> /// 添加買家信息 /// </summary> /// <returns></returns> [OperationContract] bool InsertBuyerInfo(Buyer info); } }這樣,接口標記:
ServiceContract。
方法標記:OperationContract
.net core 下調用.nett framework框架的WCF方法寫法