使用IParameterInspector, IOperationBehavior,Attribute(參數檢查器、操作行為介面和標籤)擴充WCF操作行為
開發環境: VS2008 SP1 WIN2008 SP2
WCF允許我們在端點Endpoint、訊息message、操作Operation、參數Parameter中擴充WCF。本文簡單介紹如何截獲操作的參數來擴充WCF的操作。這種擴充需要在WCF的Contract契約上加標籤來實現,不能算是真正的AOP,但是有些AOP的意思。
實現步驟:1、實現自己的參數檢查器;2、將參數檢查器放入要實現的操作行為;3、在操作Operation上加入標籤attribute
1、實現自己的參數檢查器,實現參數檢查器,在叫用作業前檢查參數是否為17位元字,在叫用作業後發送執行結果
代碼
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());
}
}
2、將參數檢查器放入要實現的操作行為
代碼
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
}
3、在操作Operation上加入標籤attribute,在操作契約中加上標籤[EntryIdValidation]
[ServiceContract]
public interface
IRelSrvContract
{
[EntryIdValidation]
[OperationContract]
bool
Rel(
string strEntryID);
}