• 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>



  • 相关阅读:
    二叉搜索树
    【树】List Leaves
    模板——dijkstra单源最短路
    余数求和——除法分块
    倍增——ST表
    线段树——内存池
    线段树——模板
    洛谷 P1498 南蛮图腾
    洛谷 P2199 最后的迷宫
    洛谷 P1495 中国剩余定理
  • 原文地址:https://www.cnblogs.com/PurpleTide/p/2200407.html
Copyright © 2020-2023  润新知