WCF 常見邏輯和代碼 2.參數檢查 BeforeCall And AfterCall
這段代碼可以直接在wcf4.0中跑...需要的人就拷貝走吧...
我經常也會忘記代碼..做個備份
雖然.net已經內置了一些類型用于檢查輸入參數 例如DataLengthAttribute
不過畢竟功能有限,實現自己的參數檢查會更強大點.
有些東西是內置無法實現的, 例如在輸入的時候檢查權限,Request還有記錄運行時間等
以下是C#代碼(這里只是一種實現, IParameterInspector 還可以被應用到其他的地方 例如面對EndPoint和Attribute)
View Code
public class ValidationBehaviorSection : BehaviorExtensionElement, IServiceBehavior
{
private const string EnabledAttributeName = "enabled";
[ConfigurationProperty(EnabledAttributeName, DefaultValue = true, IsRequired = false)]
public bool Enabled
{
get { return (bool)base[EnabledAttributeName]; }
set { base[EnabledAttributeName] = value; }
}
protected override object CreateBehavior()
{
return this;
}
public override Type BehaviorType
{
get
{
return GetType();
}
}
private ValidationParameterInspector GetInstance()
{
return new ValidationParameterInspector();
}
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
if (!Enabled)
{
return;
}
ValidationParameterInspector inspector = GetInstance();
foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
{
foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
{
// epDisp.DispatchRuntime.MessageInspectors.Add(new ValidationParameterInspector());
foreach (DispatchOperation op in epDisp.DispatchRuntime.Operations)
op.ParameterInspectors.Add(inspector);
}
}
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
public class ValidationParameterInspector : IParameterInspector
{
private DateTime startTime;
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{
}
public object BeforeCall(string operationName, object[] inputs)
{
startTime = DateTime.Now;
return null;
}
}
下面是web.confg的配置
<extensions>
<behaviorExtensions>
<add name="validator" type="{命名空間}.ValidationBehaviorSection, {dll名字}"/>
</behaviorExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior>
<validator />
</behavior>
</serviceBehaviors>
</behaviors>

浙公網安備 33010602011771號