你能在WCF服务方法中使用可选参数吗
本文关键字:参数 WCF 服务 方法 | 更新日期: 2023-09-27 17:57:32
我见过这样和这样的帖子,但它们都有几年的历史了。
我能做这样的事吗?
[OperationContract]
[FaultContract(typeof(MyCustomFault))]
List<InventoryPart> SelectMany(string partialPartNumber, string division = null);
你不能。WCF在方法签名方面有许多限制;一些限制是因为主机机制,而另一些则是因为WSDL/MEX。
尽管WCF可能会让您在服务代码中拥有默认参数、重载方法和许多其他东西,但当您托管服务时,它可能会启动,也可能不会启动,或者可能会启动但可能不会工作。这很棘手。
为了克服这一点,我所做的是,我在任何需要的地方都使用可为null的参数,然后在我的客户端代码上,我总是有一个服务层可以访问我自动生成的客户端代理;我的服务层有我想要的所有重载和可选参数。示例(脏代码):
WCF服务:
[OperationContract]
[FaultContract(typeof(MyCustomFault))]
List<InventoryPart> SelectMany(string partialPartNumber, string division, int? subDivision, bool? isActive);
客户端服务层(不是自动生成的代理,而是我编写的代理)
public List<InventoryPart> GetParts(string partialPartNumber){
return GetParts(partialPartNumber, null);
}
public List<InventoryPart> GetParts(string partialPartNumber, string division){
return GetParts(partialPartNumber, division, null);
}
public List<InventoryPart> GetParts(string partialPartNumber, string division, int? subDivision){
return GetParts(partialPartNumber, division, subDivision, null);
}
public List<InventoryPart> GetParts(string partialPartNumber, string division, int? subDivision, bool? isActive){
// This method is the one that actually calls the client proxy channels and all.
}
我的客户端应用程序消耗客户端服务层
public void LoadPartNumbers(){
var parts = ClientServiceLayer.GetParts(this.txtPartNumber.Text, null, (int) this.cboDivisions.SelectedItem );
}