如何在BeforeSendRequest中取消请求 [英] How to cancel a request in BeforeSendRequest

查看:229
本文介绍了如何在BeforeSendRequest中取消请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用IClientMessageInspector界面时,可以取消BeforeSendRequest方法中的请求吗?无论如何,返回null都会发送请求.

When using the IClientMessageInspector interface, can I cancel a request from the BeforeSendRequest method? Returning null sends the request anyway.

 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
    if(Condition)
    {
        return null; //I want cancel my send
    }
    else
    {
       return request;
    }
  }

推荐答案

可能有多种方法可以处理这种情况,但是我认为它们都涉及简单地从IClientMessageInspect.BeforeSendRequest中抛出异常以过早地结束客户端操作.引发异常的类型可能会根据使用情况的应用程序所期望的情况而有所不同,或者您可以在其他地方捕获到的异常.

There are probably multiple ways to handle this scenario, but I think they all involve simply throwing an exception out of your IClientMessageInspect.BeforeSendRequest to prematurely end the client operation. The type of exception you throw probably varies depending on what the consuming application expects in your scenario, or something you can catch upstream some where else.

就我而言,我正在构建WCF RESTful代理/路由服务.我的IClientMessageInspect需要检查绑定到我们发短信供应商的传出消息,并且除非传出电话号码在路由器代理/路由服务web.config中被白名单",否则不允许将传出消息发送到供应商的Service API.

In my case, I was building a WCF RESTful proxy/routing service. My IClientMessageInspect was required to inspect outgoing messages bound for our texting vendor, and not allow the outgoing message to be sent to the vendor's Service API unless the outbound phone number was "white listed" in the router proxy/routing service web.config

public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
    if (!WhiteList.IsWhiteListed(outboundNumber))
    {
        throw new WebFaultException<RouterServiceFault>(new RouterServiceFault {Message = $"Phone number {outboundNumber} is not white listed." }, HttpStatusCode.Forbidden);
    }

    // Save the routed to service request address so we can see it after receive reply (in correlationState)
    return request.Headers.To;
}

RouterServiceFault是一个简单的类,我可以将消息传回以显示/登录使用中的应用程序.

Where RouterServiceFault is a simple class I can pass a message back in to display/log in the consuming application.

[ServiceContract]
public class RouterServiceFault
{
    [DataMember]
    public string Message { get; set; }
}

这篇关于如何在BeforeSendRequest中取消请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆