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



  • 相关阅读:
    ant-design-vue——子组件通过$parent修改父组件的值时无效问题及解决方法
    vue——quill-editor自定义图片上传
    ES6——var、let、const三者的区别
    js——数组/对象常用方法总结
    28.最长回文子序列
    27.马拉车
    26.扫雷一次点击
    JS添加内容之方法里传AJAX参数
    JQ 实现加载其他页面的H5代码 JQ加载H5独立导航栏代码
    CentOS 7不能上网 解决方法
  • 原文地址:https://www.cnblogs.com/PurpleTide/p/2200407.html
Copyright © 2020-2023  润新知