【问题标题】:When and where to set a custom IOperationInvoker?何时何地设置自定义 IOperationInvoker?
【发布时间】:2010-11-12 09:59:29
【问题描述】:

我正在尝试扩展 WCF,以便拥有一个 RESTful Web 服务,在该服务中,对于每个操作,我都会验证 HTTP 授权标头,我使用其值来调用 Login() 方法。

登录完成后,我希望调用操作的相应方法检查是否引发了安全异常,在这种情况下,我将使用适当的 HTTP 状态代码回复自定义“拒绝访问”消息。

考虑到这一点,我认为实现一个 IEndpointBehavior 将 IOperationInvoker 的实现应用于每个操作(设置 DispatchOperation.Invoker 属性)将是一个好主意。

我决定使用装饰器设计模式来实现 IOperationInvoker。我的实现将需要另一个 IOperationInvoker 在它的构造函数中,方法调用将被委托给它。

这是我的 IOperationInvokerImplementation:

    public class BookSmarTkOperationInvoker : IOperationInvoker{

    private readonly IOperationInvoker invoker;

    public BookSmarTkOperationInvoker(IOperationInvoker decoratee)
    {
        this.invoker = decoratee;
    }

    public object[] AllocateInputs()
    {
        return this.invoker.AllocateInputs();
    }

    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        BeforeOperation(); // Where there's code to perform the login using WebOperationContext.Current
        object o = null;
        try
        {
            o = this.invoker.Invoke(instance, inputs, out outputs);
        }
        catch (Exception exception)
        {
            outputs = null;
            return AfterFailedOperation(exception); // Return a custom access denied response
        }

        return o;
    }

    public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
    {
        throw new Exception("The operation invoker is not asynchronous.");
    }

    public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
    {
        throw new Exception("The operation invoker is not asynchronous.");
    }

    public bool IsSynchronous
    {
        get
        {
            return false;
        }
    }
}

我决定通过扩展我已经需要的行为 (WebHttpBehavior) 来实现 IEndpointBehavior,这样我只使用一种行为。这是我写的代码:

public class BookSmarTkEndpointBehavior : WebHttpBehavior
{
    public override void Validate(ServiceEndpoint endpoint)
    {
        base.Validate(endpoint);
    }

    public override void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
        base.AddBindingParameters(endpoint, bindingParameters);
    }

    public override void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        base.ApplyDispatchBehavior(endpoint, endpointDispatcher);

        foreach (DispatchOperation operation in endpointDispatcher.DispatchRuntime.Operations)
        {
            IOperationInvoker defaultInvoker = operation.Invoker;
            IOperationInvoker decoratorInvoker = new BookSmarTkOperationInvoker(defaultInvoker);
            operation.Invoker = decoratorInvoker;

            Console.Write("Before: " + ((object)defaultInvoker ?? "null"));
            Console.WriteLine(" After: " + operation.Invoker);
        }
    }

    public override void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        base.ApplyClientBehavior(endpoint, clientRuntime);
        throw new Exception("The BookSmarTkEndointBehavior cannot be used in client endpoints.");
    }
}

现在问题来了:

  1. 在 IOperationInvoker 中仅调用构造函数,其他方法均未调用。
  2. 被装饰者 IOperationInvoker(在装饰器的构造函数中传递的那个)是 null

我猜测可能是来自其他行为的其他代码随后在 OperationDispatcher.Invoker 设置中设置了另一个 IOperationInvoker。因此,覆盖我的。 这将清楚地解释我的情况。

发生了什么,我该怎么办?

我的服务是自托管的。

如果您需要查看,这里是我在 system.serviceModel 下的 app.config 文件中的配置。

<services>
  <service name="BookSmarTk.Web.Service.BookSmarTkService">
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8080/service"/>
      </baseAddresses>
    </host>
    <endpoint  
      address=""
      behaviorConfiguration="BookSmaTkEndpointBehavior"
      binding="webHttpBinding" 
      bindingConfiguration="BookSmarTkBinding"
      contract="BookSmarTk.Web.Service.BookSmarTkService">
    </endpoint>
  </service>
</services>

<behaviors>
  <serviceBehaviors>
    <behavior name ="BookSmartkServiceBehavior">
      <serviceDebug httpHelpPageEnabled="true" httpHelpPageUrl="/help.htm" includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="BookSmaTkEndpointBehavior">
      <!--<webHttp/>-->
      <bookSmarTkEndpointBehavior />
    </behavior>
  </endpointBehaviors>
</behaviors>

<bindings>
  <webHttpBinding>
    <binding name="BookSmarTkBinding">
    </binding>
  </webHttpBinding>
</bindings>

<extensions>
  <behaviorExtensions>
    <add name="bookSmarTkEndpointBehavior" type="BookSmarTk.Web.Service.BookSmarTkEndpointBehaviorElement, BookSmarTk.Web.Service, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  </behaviorExtensions>
</extensions>

我读到这里,我深深地感谢你。真的,谢谢!

【问题讨论】:

    标签: wcf


    【解决方案1】:

    您必须创建一个 IOperationBehavior 实现器,而不是在 ApplyDispatchBehavior() 方法中设置调用程序:

     public class MyOperationBehavior: IOperationBehavior
     {
      public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
      {
      }
    
      public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
      {
      }
    
      public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
      {
       dispatchOperation.Invoker = new BookSmarTkOperationInvoker(dispatchOperation.Invoker);
      }
    
      public void Validate(OperationDescription operationDescription)
      {
      }
     }
    

    然后在 ApplyDispatchBehavior() 处设置该行为:

      public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
      {
        foreach (var operation in endpoint.Contract.Operations) {
          if (operation.Behaviors.Contains(typeof(MyOperationBehavior)))
           continue;
    
          operation.Behaviors.Add(new MyOperationBehavior());
       }
      }
    

    【讨论】:

      【解决方案2】:

      我正在构建类似的东西(我认为 - 没有时间查看您的所有代码),但以不同的方式进行。

      为此,我使用以下方法:

      • IMessageInspector 用于读取传入的 HTTP 请求消息标头(在这种情况下,从 cookie 中提取会话 ID 并从缓存中检索会话对象)。
      • IPrincipal 和 IAuthorizationPolicy 的组合来实现我自己的自定义授权代码(WCF 将自动调用我的代码来请求具有属性“[PrincipalPermission(SecurityAction.Demand, Role="somerole")] 的 Web 服务方法' 设置)。
      • 一个 IErrorHandler,它从 Web 服务方法中捕获任何未捕获的异常(包括授权失败时抛出的权限被拒绝异常 - 即您在 IPrincipal 中实现的 IsRole 方法返回 false)。如果您捕获了 security denied 异常,则可以使用 WebOperationContext.Current 为响应消息设置自定义 HTTP 错误代码。
      • 自定义行为(IContractBehavior - 但您也可以使用 EndPoint 或 Service 行为或任何您想要的行为)在运行时创建上述所有内容并将它们附加到适当的端点。

      【讨论】:

        【解决方案3】:

        我知道这已经很老了,但对我来说Alexey's answer 工作。但是,仅当 ApplyDispatchBehaviour 方法调用基方法时。像这样:

        public override void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
                base.ApplyDispatchBehavior(endpoint, endpointDispatcher);
        
                foreach (var operation in endpoint.Contract.Operations)
                {
                    if (operation.Behaviors.Contains(typeof(AccessControlOperationBehaviour)))
                        continue;
            
                    operation.Behaviors.Add(new AccessControlOperationBehaviour());
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-01-22
          • 2015-10-01
          • 1970-01-01
          • 2023-03-18
          • 1970-01-01
          • 2020-09-03
          • 1970-01-01
          相关资源
          最近更新 更多