public class EntryIdInspector : IParameterInspector { public int intParamIndex { get; set; } string EntryIdFormat = @"\d{17}"; public EntryIdInspector(): this(0){ } public EntryIdInspector(int intParamIndex) { this.intParamIndex = intParamIndex; } public object BeforeCall(string operationName, object[] inputs) { string strEntryId = inputs[this.intParamIndex] as string; if (!Regex.IsMatch(strEntryId, this.EntryIdFormat, RegexOptions.None)) { MessageQueue mq = new MessageQueue(@".\private$\msgqueue"); mq.Send( "Parameter is not valid when call " + operationName + " at " + DateTime.Now.ToLongDateString()); throw new FaultException( "Invalid Entry ID format. Required format: ##################"); } return null; } public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) { MessageQueue mq = new MessageQueue(@".\private$\msgqueue"); string strResult = returnValue.ToString(); mq.Send("Client call " + operationName + ":" + strResult + " at " + DateTime.Now.ToLongDateString()); } }
public class EntryIdValidation : Attribute, IOperationBehavior { #region IOperationBehavior Members public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { EntryIdInspector EntryIdInspector = new EntryIdInspector(); clientOperation.ParameterInspectors.Add(EntryIdInspector); } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { EntryIdInspector EntryIdInspector = new EntryIdInspector(); dispatchOperation.ParameterInspectors.Add(EntryIdInspector); } public void Validate(OperationDescription operationDescription) { } #endregion }
在操作Operation上加入标签attribute,在操作契约中加上标签[EntryIdValidation]
[ServiceContract] public interface IRelSrvContract { [EntryIdValidation] [OperationContract] bool Rel(string strEntryID); }