首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >WCF:从OperationContext检索MethodInfo

WCF:从OperationContext检索MethodInfo
EN

Stack Overflow用户
提问于 2009-05-12 13:41:23
回答 4查看 11.4K关注 0票数 19

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

OperationContext.Current.IncomingMessageHeaders.Action

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

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-10-01 17:22:37

我花了很长时间,但我确实找到了一种比找到并艰难地浏览整个合同更好的方法:

代码语言:javascript
复制
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更快、更可靠。

票数 26
EN

Stack Overflow用户

发布于 2011-04-12 02:44:52

如果OperationContext.CurrentIncomingMessageHeaders.Action为null,您可以这样做--这有点简洁:

代码语言:javascript
复制
string actionName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string;
Type hostType = operationContext.Host.Description.ServiceType;
MethodInfo method = hostType.GetMethod(actionName);
票数 15
EN

Stack Overflow用户

发布于 2012-04-05 16:40:48

基于@航空和@TimDog的回答,以及this SO question,我提出了一个解决方案,即应该同时适用于REST和SOAP

代码语言:javascript
复制
///<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);
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/852860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档