如何在调用WCF服务之前弹出一个确认对话框?
昨天有人在微博上问我如下一个问题:
其实这个问题可以通过WCF的扩展来完成,具体来说这个扩展涉及到一个我们不太常用的组件“InteractiveChannelInitializer”,在我的《WCF全面解析》中对它有过概括性的介绍。InteractiveChannelInitializer实现了接口IInteractiveChannelInitializer,从名称可以看出这是一个“交互性”的“信道初始化器”,在一般情况下我们用它来动态地指定客户端调用凭证(比如在弹出的登录对话框中输入用户名和密码)。而上面这个问题就可以通过自定义InteractiveChannelInitializer来实现,我为此写了一个简单的实例(源代码从这里下载)。 右图所示的是实例的运行界面。我们以Windows Form应用的方式编写了一个“计算器”,计算结果通过调用WCF服务来获取。在每次调用服务之前都会弹出一个确认对话框,真正的服务调用只有在用户确认之后方能进行。 用于实现“服务调用确认”的自定义InteractiveChannelInitializer(InvocationConfirmationInteractiveChannelInitializer)定义如下。我们在BeginDisplayInitializationUI方法中弹出一个确认对话框,并将用户的确认选择封装到一个简单的AsyncResult对象中返回。在EndDisplayInitializationUI方法中,通过AsyncResult对象确认用户是否取消本次服务调用,如果是则抛出一个自定义的InvocationCancelException异常。 1: public class InvocationConfirmationInteractiveChannelInitializer : IInteractiveChannelInitializer 3: const string ConfirmMessage = "程序执行过程涉及到WCF服务调用,是否继续?"; 5: { 7: return new SimpleAsynsResult(cancel); 9:? 11: { 13: if((bool)asyncResult.AsyncState) 15: throw new InvocationCancelException("WCF服务调用被取消"); 17: } 19:? 21: { 24: this.AsyncState = state;
26:? 28: public WaitHandle AsyncWaitHandle { get; private set; } 30: { 32: } 34: { 37: } 我们通过一个自定义的ContractBehavior(InvocationConfirmationBehaviorAttribute )将上面自定义的InvocationConfirmationInteractiveChannelInitializer应用到客户端运行时。如下面的代码片断所示,在实现的ApplyClientBehavior方法中,我们创建了一个InvocationConfirmationInteractiveChannelInitializer对象并将其添加到客户端运行时的InteractiveChannelInitializers集合中。 2: class InvocationConfirmationBehaviorAttribute : Attribute,IContractBehavior
void AddBindingParameters(ContractDescription contractDescription,ServiceEndpoint endpoint,BindingParameterCollection bindingParameters) { } 6: { 9: void ApplyDispatchBehavior(ContractDescription contractDescription,DispatchRuntime dispatchRuntime) { }
11: } 以特性形式定义的InvocationConfirmationBehaviorAttribute直接以如下的方式直接应用到作为服务契约的ICalcualtor接口中: 2: [InvocationConfirmationBehavior]
4: { 6: double Add(double x,1)">double y); partial class Form1 : Form
private void buttonCalculate_Click(object sender,EventArgs e) using (ChannelFactory<ICalculator> channelfactory = new ChannelFactory<ICalculator>("calculatorservice")) 9: ICalculator calculator = channelfactory.CreateChannel(); 11: { 13: double op2 = this.textBoxOp2.Text); 15: this.textBoxResult.Text = result.ToString();
17: catch (InvocationCancelException)
19: } 21: { 23: } 26: } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc – MVC5架构中的Identity 2.0.0建议
- asp.net-core – appsettings.json中ConnectionString中的S
- asp.net – 如何让静态Html页面通过IIS7.0中的HttpModule?
- asp.net-mvc – 自定义EditorTemplate可以为其中的相同模型
- asp.net – 如何在json结果上使用jquery选择器
- 文件上传 – 是否可以在上传文件的asp.net webapi中进行模型
- Owin错误与ASP.NET MVC应用程序
- asp.net-mvc – ASP.NET MVC 5和Web API 2 .NET要求
- asp.net-web-api – 将Application Insight与ASP API Core结
- asp.net-mvc – 如何构建URL路由?