WCF: Retrieving MethodInfo from OperationContext

后端 未结 4 1426
猫巷女王i
猫巷女王i 2020-12-13 07:20

Is there an elegant way to get the method that will be executed on a service instance from MessageInspector/AuthorizationPolicy/some other extension point? I could use

4条回答
  •  Happy的楠姐
    2020-12-13 08:07

    Based on @Aaronaught and @TimDog 's answers, and this SO question I came up with a solution that should work for both REST and SOAP.

    ///Returns the Method info for the method (OperationContract) that is called in this WCF request.
    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);
    }
    

提交回复
热议问题