WCF 参数拦截器 应用于参数服务参数的校验
通过实现接口IParameterInspector来达到对在调用前或者调用后对参数的拦截作用
具体步骤
1. 新建一个wcf服务应用工程,定义一个服务
[ServiceContract(Namespace="http://www.swzsoft.cn")]
public interface IService1 {
[ParameOperatorBehavior]
[OperationContract]
string register_user(string username, string password, int age);
}
服务接口接口实现
public class Service1 : IService1 {
public string register_user(string username, string password, int age) {
return username + ":" + password + ":" + age.ToString();
}
}
从服务契约我们知道该服务实例包含三个参数分别为:
username : string
password : string
age : int
现在通过实现IParameterInspector来实现对该服务实例的参数拦截
public class ParameInspector : IParameterInspector {
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) {
//throw new NotImplementedException();
}
public object BeforeCall(string operationName, object[] inputs) {
if (string.IsNullOrWhiteSpace(inputs[0].ToString()) ||
inputs[0].ToString().Length > 16) {
throw new System.ServiceModel.FaultException("UserName");
}
if (string.IsNullOrWhiteSpace(inputs[1].ToString()) ||
inputs[1].ToString().Length > 16) {
throw new System.ServiceModel.FaultException("Password");
}
int age = Convert.ToInt32(inputs[2].ToString());
if (age < 18) {
throw new System.ServiceModel.FaultException("Age");
}
return null;
}
}
public class ParameOperatorBehavior : Attribute, IOperationBehavior {
public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) {
// throw new NotImplementedException();
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) {
// throw new NotImplementedException();
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) {
// throw new NotImplementedException();
dispatchOperation.ParameterInspectors.Add(new ParameInspector());
}
public void Validate(OperationDescription operationDescription) {
//throw new NotImplementedException();
}
}
ParameOperatorBehavior 自定义属性,这里主要实现
IOperationBehavior.ApplyDispatchBehavior添加自定的拦截器

浙公网安备 33010602011771号