WCF:从OperationContext检索MethodInfo

Dmi*_*sky 18 .net wcf

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

OperationContext.Current.IncomingMessageHeaders.Action

但我希望有一些方法可以做到这一点,而无需手动匹配SOAP操作与OperationContracts.

我要做的是在执行之前检查方法的属性.

Aar*_*ght 26

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

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);
Run Code Online (Sandbox Code Playgroud)

你有.您可以获取属性或执行您喜欢的任何其他操作.

注意:您可能想尝试在DispatchRuntime中使用OperationSelector.我发现的问题是,在我的情况下,在处理的特定阶段,OperationSelector是一个空引用.如果您可以访问此属性,则使用它比使用上面的"扫描"OperationCollection更快更可靠.

  • 如果在OperationContract中重命名该操作,则这不起作用. (2认同)

Tim*_*Dog 14

如果OperationContext.CurrentIncomingMessageHeaders.Action为null,你可以这样做 - 它有点terser:

string actionName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string;
Type hostType = operationContext.Host.Description.ServiceType;
MethodInfo method = hostType.GetMethod(actionName);
Run Code Online (Sandbox Code Playgroud)


jar*_*ics 7

基于@Aaronaught和@TimDog的答案,以及这个问题,我想出了一个适用于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);
}
Run Code Online (Sandbox Code Playgroud)