代码之家  ›  专栏  ›  技术社区  ›  Dmitry Ornatsky

WCF:从OperationContext检索MethodInfo

  •  17
  • Dmitry Ornatsky  · 技术社区  · 17 年前

    是否有一种优雅的方法可以从MessageInspector/AuthorizationPolicy/某个其他扩展点获取将在服务实例上执行的方法?我可以用

    但我希望有一些方法可以做到这一点,而不必手动将SOAP操作与OperationContracts匹配。

    4 回复  |  直到 15 年前
        1
  •  26
  •   Aaronaught    17 年前

    这花了我很长时间,但我确实找到了一种比找到并苦读整个合同更好的方法:

    string action = operationContext.IncomingMessageHeaders.Action;
    DispatchOperation operation = 
        operationContext.EndpointDispatcher.DispatchRuntime.Operations.FirstOrDefault(o =>
            o.Action == action);
    // Insert your own error-handling here if (operation == null)
    Type hostType = operationContext.Host.Description.ServiceType;
    MethodInfo method = hostType.GetMethod(operation.Name);
    

    注意:您可能会尝试在DispatchRuntime中使用OperationSelector。我发现的问题是,在我的例子中,在处理的特定阶段,OperationSelector是一个空引用。如果您有权访问此属性,则使用它可能比如上所述“扫描”OperationCollection更快、更可靠。

        2
  •  15
  •   TimDog    15 年前

    OperationContext.CurrentIncomingMessageHeaders.Action 为空,您可以这样做--它有点简洁:

    string actionName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string;
    Type hostType = operationContext.Host.Description.ServiceType;
    MethodInfo method = hostType.GetMethod(actionName);
    
        3
  •  8
  •   Community Mohan Dere    9 年前

    基于@Aaronaught和@TimDog的答案,以及 this SO question 我想出了一个解决办法 应该对REST和SOAP都有效

    ///<summary>Returns the Method info for the method (OperationContract) that is called in this WCF request.</summary>
    System.Reflection.MethodInfo GetActionMethodInfo(System.ServiceModel.OperationContext operationContext ){
        string bindingName = operationContext.EndpointDispatcher.ChannelDispatcher.BindingName;
        string methodName;
        if(bindingName.Contains("WebHttpBinding")){
                //REST request
                methodName = (string) operationContext.IncomingMessageProperties["HttpOperationName"];
        }else{
                //SOAP request
                string action = operationContext.IncomingMessageHeaders.Action;
                methodName = operationContext.EndpointDispatcher.DispatchRuntime.Operations.FirstOrDefault(o =>o.Action == action).Name;
        }
        // Insert your own error-handling here if (operation == null)
        Type hostType = operationContext.Host.Description.ServiceType;
        return hostType.GetMethod(methodName);
    }
    
        4
  •  1
  •   Krzysztof Kozmic    17 年前

    Castle WCF集成工具使您能够通过使用DynamicProxy代理实现这一点(在许多有用的事情中)。 看一看 here .

    推荐文章