Use iparameterinspector, ioperationbehavior, attribute (parameter checker, operation behavior interface, and tag) to extend the WCF Operation Behavior
Development Environment: vs2008 SP1 win2008 SP2
WCF allows us to extend WCF in endpoint, message, operation, parameter. This article briefly introduces how to intercept operation parameters to extend the operation of WCF. This kind of extension needs to be implemented by adding labels to the contract Contract of WCF. It cannot be regarded as the actual AOP, but some AOP means.
Implementation steps: 1. Implement your own parameter checker; 2. Put the parameter checker into the operation to be implemented; 3. Add the label attribute to the operation.
1. Implement your own parameter Checker to implement the parameter checker. Check whether the parameter is 17 digits before calling the operation and send the execution result after calling the operation.
Code
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 newFaultexception (
"Invalid entry ID format. required format :##################");
}
Return null;
}
Public void aftercall (string operationname, object [] outputs, object returnvalue, ObjectCorrelationstate)
{
Messagequeue MQ = new messagequeue (@ ". \ private $ \ msgqueue");
String strresult =Returnvalue. tostring ();
MQ. Send ("client call" + operationname + ":" + strresult + "at" +Datetime. Now. tolongdatestring ());
}
}
2. Put the parameter checker into the operation to be implemented
Code
Public class
Entryidvalidation: attribute, ioperationbehavior
{
# Region ioperationbehavior members
Public voidAddBindingParameters (OperationDescription operationDescription,
BindingParameterCollection bindingParameters)
{
}
Public voidApplyClientBehavior (OperationDescription operationDescription,
Clientoperation)
{
Entryidinspector = newEntryidinspector ();
Clientoperation. parameterinspectors. Add (entryidinspector );
}
Public voidApplydispatchbehavior (operationdescription,
Dispatchoperation)
{
EntryIdInspector = newEntryIdInspector ();
DispatchOperation. ParameterInspectors. Add (EntryIdInspector );
}
Public voidValidate (OperationDescription operationDescription)
{
}
# Endregion
}
3. Add the label attribute to the Operation and add the label to the Operation contract.[EntryIdValidation]
[Servicecontract]
Public interface
Irelsrvcontract
{
[Entryidvalidation]
[Operationcontract]
Bool
REL (
String strentryid );
}