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>