有没有一种优雅的方法可以从MessageInspector/AuthorizationPolicy/其他扩展点获取将在服务实例上执行的方法?我可以用
OperationContext.Current.IncomingMessageHeaders.Action
但我希望有一些方法可以做到这一点,而不需要手动将SOAP操作与OperationContracts进行匹配。
我要做的是在方法执行之前检查它的属性。
发布于 2009-10-01 17:22:37
我花了很长时间,但我确实找到了一种比找到并艰难地浏览整个合同更好的方法:
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更快、更可靠。
发布于 2011-04-12 02:44:52
如果OperationContext.CurrentIncomingMessageHeaders.Action
为null,您可以这样做--这有点简洁:
string actionName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string;
Type hostType = operationContext.Host.Description.ServiceType;
MethodInfo method = hostType.GetMethod(actionName);
发布于 2012-04-05 16:40:48
基于@航空和@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);
}
https://stackoverflow.com/questions/852860
复制相似问题