响应最大压缩c#

响应最大压缩c#,c#,sabre,C#,Sabre,早上好,我在.net中找到了一个解决方案,我调用了saber讨价还价查找器max的Web服务。现在我想下载压缩信息,但响应对象返回null。我了解到您必须在SendRequest之前和Receivereply之后调用接口IClientMessageInspector,但我不知道如何继续。有人会给出一个例子或解决方案吗?谢谢服务的响应无法处理压缩响应,因此,是的,您必须在继续解压之前放置中间件以处理解压 首先,您需要将BFM WSDL作为服务导入,而不是作为web服务导入,因此: 右键单击“服务引

早上好,我在.net中找到了一个解决方案,我调用了saber讨价还价查找器max的Web服务。现在我想下载压缩信息,但响应对象返回null。我了解到您必须在SendRequest之前和Receivereply之后调用接口IClientMessageInspector,但我不知道如何继续。有人会给出一个例子或解决方案吗?谢谢

服务的响应无法处理压缩响应,因此,是的,您必须在继续解压之前放置中间件以处理解压

首先,您需要将BFM WSDL作为服务导入,而不是作为web服务导入,因此:

  • 右键单击“服务引用”,然后单击“添加服务引用…”
  • 将WSDL URL粘贴到“Address:”下,然后单击“Go”
    • 建议:下载WSDL和关联的模式,以便您可以修改它们,因为.NET在处理某些事情时存在一些问题,您可以手动修改
  • 您可以随意命名服务,在本例中,我将其称为BargainFinderMaxq_4_1_0_Srvc,在“名称空间:”下,单击“确定”
  • 然后,我创建了两个类,一个是调用BFM的类(“BFM_v410Service”),另一个是用于中间件的类(“BFMinSector”)

    让我们从bfminspect开始:

    // The inspector class has to implement both IClientMessageInspector and IEndpointBehavior interfaces
    public class BFMInspector : IClientMessageInspector, IEndpointBehavior
    {
        // This is the method to action after receiving a response from Sabre
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            try
            {
                // Get compressed response from reply and load that into a byte array.
                XmlDictionaryReader bodyReader = reply.GetReaderAtBodyContents();
                bodyReader.ReadStartElement("CompressedResponse");
                byte[] bodyByteArray = bodyReader.ReadContentAsBase64();
    
                // Create some helper variables
                StringBuilder uncompressed = new StringBuilder();
                String xmlString = "";
                XmlDocument xmlPayload = new XmlDocument();
    
                // Load the byte array into memory
                using (MemoryStream memoryStream = new MemoryStream(bodyByteArray))
                {
                    // Unzip the Stream
                    using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                    {
                        byte[] buffer = new byte[1024];
                        int readBytes;
    
                        // Unzips character by character
                        while ((readBytes = gZipStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            for (int i = 0; i < readBytes; i++)
                                // Append all characters to build the response
                                uncompressed.Append((char)buffer[i]);
                        }
                    }
    
                    xmlString = uncompressed.ToString();
                    xmlString = xmlString.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>", "");
                }
    
                // Convert the string into an XML
                xmlPayload.LoadXml(xmlString);
    
                // Create a new Message, which is what will substitute what was returned by Sabre
                Message tempMessage = Message.CreateMessage(reply.Version, null, xmlPayload.ChildNodes[0]);
    
                tempMessage.Headers.CopyHeadersFrom(reply.Headers);
                tempMessage.Properties.CopyProperties(reply.Properties);
    
                MessageBuffer bufferOfFault = tempMessage.CreateBufferedCopy(Int32.MaxValue);
    
                // Replace the reply with the new Message
                reply = bufferOfFault.CreateMessage();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // Nothing is done here, so we simply return null
            return null;
        }
    
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            // Nothing done
        }
    
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            // Add "this" as an endpoint to be inspected
            clientRuntime.MessageInspectors.Add(this);
        }
    
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            // Nothing done
        }
    
        public void Validate(ServiceEndpoint endpoint)
        {
            // Nothing done
        }
    }
    
    // BFM calling class
    public class BFM_v410Service
    {
        // The constructor and CreateRequest simeply create a complete request
        private BargainFinderMaxRQRequest service;
        private OTA_AirLowFareSearchRQ request;
        public OTA_AirLowFareSearchRS response;
        private string endpoint;
    
        public BFM_v410Service(string token, string pcc, string convId, string endpoint)
        {
            CreateRequest(pcc, true);
            this.endpoint = endpoint;
    
            service = new BargainFinderMaxRQRequest()
            {
                MessageHeader = new BargainFinderMaxRQ_3_4_0_Srvc.MessageHeader()
                {
                    From = new From()
                    {
                        PartyId = new PartyId[]
                    {
                        new PartyId()
                        {
                            Value = pcc
                        }
                    }
                    },
                    To = new To()
                    {
                        PartyId = new PartyId[]
                    {
                        new PartyId()
                        {
                            Value = endpoint
                        }
                    }
                    },
                    ConversationId = convId,
                    CPAId = pcc,
                    Service = new Service()
                    {
                        Value = "BargainFinderMaxRQ"
                    },
                    Action = "BargainFinderMaxRQ",
                    MessageData = new MessageData()
                    {
                        Timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssK")
                    }
                },
                OTA_AirLowFareSearchRQ = request,
                Security = new Security()
                {
                    BinarySecurityToken = token
                }
            };
        }
    
        private void CreateRequest(string pcc, bool compressed)
        {
            request = new OTA_AirLowFareSearchRQ()
            {
                Version = "3.4.0",
                POS = new SourceType[]
                {
                    new SourceType()
                    {
                        PseudoCityCode = pcc,
                        RequestorID = new UniqueID_Type()
                        {
                            ID = "1",
                            Type = "1",
                            CompanyName = new CompanyNameType()
                            {
                                Code = "TN",
                                Value = "TN"
                            }
                        }
                    }
                },
                OriginDestinationInformation = new OTA_AirLowFareSearchRQOriginDestinationInformation[]
                {
                    new OTA_AirLowFareSearchRQOriginDestinationInformation()
                    {
                        RPH = "1",
                        Item = "2018-09-21T11:00:00",
                        ItemElementName = ItemChoiceType.DepartureDateTime,
                        OriginLocation = new OriginDestinationInformationTypeOriginLocation()
                        {
                            LocationCode = "MVD"
                        },
                        DestinationLocation = new OriginDestinationInformationTypeDestinationLocation()
                        {
                            LocationCode = "KRK"
                        }
                    },
                    new OTA_AirLowFareSearchRQOriginDestinationInformation()
                    {
                        RPH = "2",
                        Item = "2018-09-28T11:00:00",
                        ItemElementName = ItemChoiceType.DepartureDateTime,
                        OriginLocation = new OriginDestinationInformationTypeOriginLocation()
                        {
                            LocationCode = "KRK"
                        },
                        DestinationLocation = new OriginDestinationInformationTypeDestinationLocation()
                        {
                            LocationCode = "MVD"
                        }
                    }
                },
                TravelerInfoSummary = new TravelerInfoSummaryType()
                {
                    AirTravelerAvail = new TravelerInformationType[]
                    {
                        new TravelerInformationType()
                        {
                            PassengerTypeQuantity = new PassengerTypeQuantityType[]
                            {
                                new PassengerTypeQuantityType()
                                {
                                    Code = "ADT",
                                    Quantity = "1"
                                }
                            }
                        }
                    }
                },
                TPA_Extensions = new OTA_AirLowFareSearchRQTPA_Extensions()
                {
                    IntelliSellTransaction = new TransactionType()
                    {
                        RequestType = new TransactionTypeRequestType()
                        {
                            Name = "50ITINS"
                        },
                        CompressResponse = new TransactionTypeCompressResponse()
                        {
                            Value = compressed
                        }
                    }
                }
            };
        }
    
        public void Execute()
        {
            try
            {
                // Instanciate the Inspector
                BFMInspector inspector = new BFMInspector();
    
                // Select the URL you'll be sending the request. I've passed this as a parameter in the constructor
                EndpointAddress url = new EndpointAddress(new Uri(endpoint));
    
                // Create a binding, with a couple of characteristics, because of the size of the response
                Binding binding = new BasicHttpsBinding()
                {
                    MaxReceivedMessageSize = Int32.MaxValue,
                    MaxBufferSize = Int32.MaxValue
                };
    
                // Create the executable the BargainFinderMaxPortTypeClient variable, which will allow me to call the service
                BargainFinderMaxPortTypeClient execute = new BargainFinderMaxPortTypeClient(binding, url);
    
                // Add the middleware. Here's where ApplyClientBehavior is called behind the scene and adds itself
                execute.Endpoint.EndpointBehaviors.Add(inspector);
    
                // Call BFM and successfully get the response as an OTA_AirLowFareSearchRS object
                response = execute.BargainFinderMaxRQ(ref service.MessageHeader, ref service.Security, request);
                Console.WriteLine(response);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    
    static void Main(string[] args)
    {
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    
        string token = @"Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/RESA!ICESMSLB\/RES.LB!-3146624380791354996!413892!0!1!E2E-1";
        string pcc = "XXXX";
        string convId = "HERE GOES YOUR CONVERSATION ID";
        string endpoint = "https://webservices.havail.sabre.com";
    
        BFM_v410Service bfm340 = new BFM_v410Service(token, pcc, convId, endpoint);
        bfm410.Execute();
    }
    
    然后,只需从控制台应用程序调用它:

    // The inspector class has to implement both IClientMessageInspector and IEndpointBehavior interfaces
    public class BFMInspector : IClientMessageInspector, IEndpointBehavior
    {
        // This is the method to action after receiving a response from Sabre
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            try
            {
                // Get compressed response from reply and load that into a byte array.
                XmlDictionaryReader bodyReader = reply.GetReaderAtBodyContents();
                bodyReader.ReadStartElement("CompressedResponse");
                byte[] bodyByteArray = bodyReader.ReadContentAsBase64();
    
                // Create some helper variables
                StringBuilder uncompressed = new StringBuilder();
                String xmlString = "";
                XmlDocument xmlPayload = new XmlDocument();
    
                // Load the byte array into memory
                using (MemoryStream memoryStream = new MemoryStream(bodyByteArray))
                {
                    // Unzip the Stream
                    using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                    {
                        byte[] buffer = new byte[1024];
                        int readBytes;
    
                        // Unzips character by character
                        while ((readBytes = gZipStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            for (int i = 0; i < readBytes; i++)
                                // Append all characters to build the response
                                uncompressed.Append((char)buffer[i]);
                        }
                    }
    
                    xmlString = uncompressed.ToString();
                    xmlString = xmlString.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>", "");
                }
    
                // Convert the string into an XML
                xmlPayload.LoadXml(xmlString);
    
                // Create a new Message, which is what will substitute what was returned by Sabre
                Message tempMessage = Message.CreateMessage(reply.Version, null, xmlPayload.ChildNodes[0]);
    
                tempMessage.Headers.CopyHeadersFrom(reply.Headers);
                tempMessage.Properties.CopyProperties(reply.Properties);
    
                MessageBuffer bufferOfFault = tempMessage.CreateBufferedCopy(Int32.MaxValue);
    
                // Replace the reply with the new Message
                reply = bufferOfFault.CreateMessage();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // Nothing is done here, so we simply return null
            return null;
        }
    
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            // Nothing done
        }
    
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            // Add "this" as an endpoint to be inspected
            clientRuntime.MessageInspectors.Add(this);
        }
    
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            // Nothing done
        }
    
        public void Validate(ServiceEndpoint endpoint)
        {
            // Nothing done
        }
    }
    
    // BFM calling class
    public class BFM_v410Service
    {
        // The constructor and CreateRequest simeply create a complete request
        private BargainFinderMaxRQRequest service;
        private OTA_AirLowFareSearchRQ request;
        public OTA_AirLowFareSearchRS response;
        private string endpoint;
    
        public BFM_v410Service(string token, string pcc, string convId, string endpoint)
        {
            CreateRequest(pcc, true);
            this.endpoint = endpoint;
    
            service = new BargainFinderMaxRQRequest()
            {
                MessageHeader = new BargainFinderMaxRQ_3_4_0_Srvc.MessageHeader()
                {
                    From = new From()
                    {
                        PartyId = new PartyId[]
                    {
                        new PartyId()
                        {
                            Value = pcc
                        }
                    }
                    },
                    To = new To()
                    {
                        PartyId = new PartyId[]
                    {
                        new PartyId()
                        {
                            Value = endpoint
                        }
                    }
                    },
                    ConversationId = convId,
                    CPAId = pcc,
                    Service = new Service()
                    {
                        Value = "BargainFinderMaxRQ"
                    },
                    Action = "BargainFinderMaxRQ",
                    MessageData = new MessageData()
                    {
                        Timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssK")
                    }
                },
                OTA_AirLowFareSearchRQ = request,
                Security = new Security()
                {
                    BinarySecurityToken = token
                }
            };
        }
    
        private void CreateRequest(string pcc, bool compressed)
        {
            request = new OTA_AirLowFareSearchRQ()
            {
                Version = "3.4.0",
                POS = new SourceType[]
                {
                    new SourceType()
                    {
                        PseudoCityCode = pcc,
                        RequestorID = new UniqueID_Type()
                        {
                            ID = "1",
                            Type = "1",
                            CompanyName = new CompanyNameType()
                            {
                                Code = "TN",
                                Value = "TN"
                            }
                        }
                    }
                },
                OriginDestinationInformation = new OTA_AirLowFareSearchRQOriginDestinationInformation[]
                {
                    new OTA_AirLowFareSearchRQOriginDestinationInformation()
                    {
                        RPH = "1",
                        Item = "2018-09-21T11:00:00",
                        ItemElementName = ItemChoiceType.DepartureDateTime,
                        OriginLocation = new OriginDestinationInformationTypeOriginLocation()
                        {
                            LocationCode = "MVD"
                        },
                        DestinationLocation = new OriginDestinationInformationTypeDestinationLocation()
                        {
                            LocationCode = "KRK"
                        }
                    },
                    new OTA_AirLowFareSearchRQOriginDestinationInformation()
                    {
                        RPH = "2",
                        Item = "2018-09-28T11:00:00",
                        ItemElementName = ItemChoiceType.DepartureDateTime,
                        OriginLocation = new OriginDestinationInformationTypeOriginLocation()
                        {
                            LocationCode = "KRK"
                        },
                        DestinationLocation = new OriginDestinationInformationTypeDestinationLocation()
                        {
                            LocationCode = "MVD"
                        }
                    }
                },
                TravelerInfoSummary = new TravelerInfoSummaryType()
                {
                    AirTravelerAvail = new TravelerInformationType[]
                    {
                        new TravelerInformationType()
                        {
                            PassengerTypeQuantity = new PassengerTypeQuantityType[]
                            {
                                new PassengerTypeQuantityType()
                                {
                                    Code = "ADT",
                                    Quantity = "1"
                                }
                            }
                        }
                    }
                },
                TPA_Extensions = new OTA_AirLowFareSearchRQTPA_Extensions()
                {
                    IntelliSellTransaction = new TransactionType()
                    {
                        RequestType = new TransactionTypeRequestType()
                        {
                            Name = "50ITINS"
                        },
                        CompressResponse = new TransactionTypeCompressResponse()
                        {
                            Value = compressed
                        }
                    }
                }
            };
        }
    
        public void Execute()
        {
            try
            {
                // Instanciate the Inspector
                BFMInspector inspector = new BFMInspector();
    
                // Select the URL you'll be sending the request. I've passed this as a parameter in the constructor
                EndpointAddress url = new EndpointAddress(new Uri(endpoint));
    
                // Create a binding, with a couple of characteristics, because of the size of the response
                Binding binding = new BasicHttpsBinding()
                {
                    MaxReceivedMessageSize = Int32.MaxValue,
                    MaxBufferSize = Int32.MaxValue
                };
    
                // Create the executable the BargainFinderMaxPortTypeClient variable, which will allow me to call the service
                BargainFinderMaxPortTypeClient execute = new BargainFinderMaxPortTypeClient(binding, url);
    
                // Add the middleware. Here's where ApplyClientBehavior is called behind the scene and adds itself
                execute.Endpoint.EndpointBehaviors.Add(inspector);
    
                // Call BFM and successfully get the response as an OTA_AirLowFareSearchRS object
                response = execute.BargainFinderMaxRQ(ref service.MessageHeader, ref service.Security, request);
                Console.WriteLine(response);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    
    static void Main(string[] args)
    {
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    
        string token = @"Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/RESA!ICESMSLB\/RES.LB!-3146624380791354996!413892!0!1!E2E-1";
        string pcc = "XXXX";
        string convId = "HERE GOES YOUR CONVERSATION ID";
        string endpoint = "https://webservices.havail.sabre.com";
    
        BFM_v410Service bfm340 = new BFM_v410Service(token, pcc, convId, endpoint);
        bfm410.Execute();
    }
    

    希望这有帮助

    你什么都不用做。WCF支持HTTP压缩。Sabre在上启用HTTP压缩,而不是。不要使用他们的自定义压缩调用-它仍然是GZip,它压缩身体的一部分,但您必须编写代码来解压缩它。PS Fiddler可以解压缩压缩的HTTP响应。在开发过程中,检查响应、检查内容、错误消息等是必不可少的。如果您使用自定义压缩,那么最终将得到一个blob,您必须在检查之前在代码中对其进行解压缩。使调试和测试变得有点困难