如何动态更改WCF自定义行为中的URL

Nea*_*ers 7 wcf biztalk biztalk-2010 c#-4.0

类定义如下:

public class BizTalkRESTTransmitHandler : IClientMessageInspector
Run Code Online (Sandbox Code Playgroud)

我是这个签名的方法:

public object BeforeSendRequest(ref Message request, IClientChannel channel)
Run Code Online (Sandbox Code Playgroud)

所以我认为我需要操纵通道对象.

原因是这是在BizTalk 2010 SendPort中使用以支持JSON.到目前为止我试过这个:

if (channel.RemoteAddress.Uri.AbsoluteUri == "http://api-stage2.mypartner.com/rest/events/2/"
    || channel.RemoteAddress.Uri.AbsoluteUri == "http://api.mypartner.com/rest/events/2/")
{
    //TODO - "boxout" will become a variable obtained by parsing the message
    Uri newUri = new Uri(channel.RemoteAddress.Uri.AbsoluteUri + "boxout");
    channel.RemoteAddress.Uri = newUri; 

}
Run Code Online (Sandbox Code Playgroud)

上面给出了编译错误:"System.ServiceModel.EndpointAddress.Uri"无法分配给它 - 它只是就绪"RemoteAddress似乎也是只读的.

我引用了这些问题,但他们没有使用频道对象. 指定一个URL来Url.AbsoluteUri在ASP.NETWCF在运行时更改端点地址 ,但他们似乎没有被处理的通道对象.

更新1:我尝试了以下内容:

//try create new channel to change URL 
WebHttpBinding myBinding = new WebHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress(newURL);
ChannelFactory<IClientChannel> myChannelFactory = new ChannelFactory<IClientChannel>(myBinding, myEndpoint); //Change to you WCF interface
IClientChannel myNewChannel = myChannelFactory.CreateChannel();
channel = myNewChannel;  //replace the channel parm passed to us 
Run Code Online (Sandbox Code Playgroud)

但它给出了这个错误:System.InvalidOperationException:尝试获取IClientChannel的合同类型,但该类型不是ServiceContract,也不继承ServiceContract.

Ric*_*ual 2

IClientMessageInspector不是操作Channel 的正确位置,您应该使用IEndpointBehavior

来自MSDN

实现可用于扩展服务或客户端应用程序中端点的运行时行为的方法。

这是一个简单的例子:

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
    Uri endpointAddress = endpoint.Address.Uri;
    string address = endpointAddress.ToString();

    if (address == "http://api-stage2.mypartner.com/rest/events/2/"
    || address == "http://api.mypartner.com/rest/events/2/")
    {
        //TODO - "boxout" will become a variable obtained by parsing the message
        Uri newUri = new Uri(address + "boxout");
        ServiceHostBase host = endpointDispatcher.ChannelDispatcher.Host;
        ChannelDispatcher newDispatcher = this.CreateChannelDispatcher(host, endpoint, newUri);
        host.ChannelDispatchers.Add(newDispatcher);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里您可以阅读 Carlos Figueira 的精彩帖子IEndpointBehaviorhttps://blogs.msdn.microsoft.com/carlosfigueira/2011/04/04/wcf-extensibility-iendpointbehavior/

另一种选择是使用 WCF 实现简单的路由,这里是一个示例链接: 基于查询参数的 WCF REST 服务 url 路由

希望能帮助到你。