繁体   English   中英

在发送前更改Soap XML请求

[英]Change Soap XML Request prior sending

我对这个肥皂消息和东西不熟悉,我在使用WebService时遇到了一些麻烦,我使用WSDL.exe创建了一个类,我遇到的第一个问题是命令执行时,它使用var []创建了一个参数[]至此我不得不替换一个var [](数组)。

然后编译成功,现在我遇到了一些问题,我也不知道如何解决它:

我发送的请求是这个:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <emitirWS xmlns="http://neon.stoconsulting.com/NeonEmisionWS/NeonEmisionWS?wsdl">
            <comprobante serie="W" folio="143" formaPago="01" condicionesDePago="CONTADO" tipoCambio="1.000000" moneda="MXN" metodoPago="PUE" lugarExpedicion="54080" tipoComprobante="I" subTotal="827.586207" descuento="0.000000" total="960.00" documentoErp="143" usoCfdi="G03" tipoDocumento="1">
                <envioCfdi enviarXml="1" enviarPdf="1" enviarZip="0" emails="felipe.pinav@gmail.com" />
                <emisor rfc="ASM160607Q43" nombre="ARTHUR AND SONS MEXICO" regimenFiscal="601" idEmisorSto="1" idEmisorErp="1" />
                <sucursal rfc="ASM160607Q43" nombre="Plaza Polanco" regimenFiscal="601" idEmisorSto="2" idEmisorErp="2" numeroExterior="411" calle="Avenida Palmas" colonia="Miguel Hidalgo" referencia="" municipio="Toluca" estado="Edo. de México" pais="Mexico" codigoPostal="54080" email="hola@arthursons.com" idTipoEmisor="2" idEmisorPadre="1" estatusRegistro="1" />
                <receptor rfc="PIVF810724LW9" nombre="Felipe Pina Vera" regimenFiscal="622" usoCfdi="G01" idReceptoSto="1" idReceptorErp="1" numeroExterior="141A" calle="Viveros de Coyoacán" colonia="Viveros de la Loma" municipio="Tlalnepantla" estado="Edo. de México" pais="Mexico" codigoPostal="54080" email="felipe.pinav@gmail.com" idEmisorPadre="0" estatusRegistro="1" />
                <conceptos claveProdServ="42142901" cantidad="1.000000" claveUnidad="H87" unidad="Pieza" numIdentificacion="5" descripcion="BENSEN - AZUL" valorUnitario="827.586207" importe="827.586207" descuento="0.000000" xmlns="">
                    <impuestos>
                        <trasladados base="827.586207" impuesto="002" tipoFactor="Tasa" tasaOCuota="0.160000" importe="132.413793" />
                    </impuestos>
                </conceptos>
                <impuestos totalImpuestosRetenidos="0.000000" totalImpuestosTrasladados="132.413793" xmlns="">
                    <trasladados impuesto="002" tipoFactor="Tasa" tasaOCuota="0.160000" importe="132.413793" />
                </impuestos>
            </comprobante>
        </emitirWS>
    </soap:Body>
</soap:Envelope>

当到达服务器时,由于请求的格式不正确,因此无法进行处理,正确的格式为:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:neon="http://neon.stoconsulting.com/NeonEmisionWS/NeonEmisionWS?wsdl">
    <soap:Body>
        <neon:emitirWS>
            <comprobante serie="W" folio="143" formaPago="01" condicionesDePago="CONTADO" tipoCambio="1.000000" moneda="MXN" metodoPago="PUE" lugarExpedicion="54080" tipoComprobante="I" subTotal="827.586207" descuento="0.000000" total="960.00" documentoErp="143" usoCfdi="G03" tipoDocumento="1">
                <envioCfdi enviarXml="1" enviarPdf="1" enviarZip="0" emails="felipe.pinav@gmail.com" />
                <emisor rfc="ASM160607Q43" nombre="ARTHUR AND SONS MEXICO" regimenFiscal="601" idEmisorSto="1" idEmisorErp="1" />
                <sucursal rfc="ASM160607Q43" nombre="Plaza Polanco" regimenFiscal="601" idEmisorSto="2" idEmisorErp="2" numeroExterior="411" calle="Avenida Palmas" colonia="Miguel Hidalgo" referencia="" municipio="Toluca" estado="Edo. de México" pais="Mexico" codigoPostal="54080" email="hola@arthursons.com" idTipoEmisor="2" idEmisorPadre="1" estatusRegistro="1" />
                <receptor rfc="PIVF810724LW9" nombre="Felipe Pina Vera" regimenFiscal="622" usoCfdi="G01" idReceptoSto="1" idReceptorErp="1" numeroExterior="141A" calle="Viveros de Coyoacán" colonia="Viveros de la Loma" municipio="Tlalnepantla" estado="Edo. de México" pais="Mexico" codigoPostal="54080" email="felipe.pinav@gmail.com" idEmisorPadre="0" estatusRegistro="1" />
                <conceptos claveProdServ="42142901" cantidad="1.000000" claveUnidad="H87" unidad="Pieza" numIdentificacion="5" descripcion="BENSEN - AZUL" valorUnitario="827.586207" importe="827.586207" descuento="0.000000">
                    <impuestos>
                        <trasladados base="827.586207" impuesto="002" tipoFactor="Tasa" tasaOCuota="0.160000" importe="132.413793" />
                    </impuestos>
                </conceptos>
                <impuestos totalImpuestosRetenidos="0.000000" totalImpuestosTrasladados="132.413793">
                    <trasladados impuesto="002" tipoFactor="Tasa" tasaOCuota="0.160000" importe="132.413793" />
                </impuestos>
            </comprobante>
        </neon:emitirWS>
    </soap:Body>
</soap:Envelope>

我需要切换:

1)在信封节点中,我需要添加一个新属性:

xmlns:neon="http://neon.stoconsulting.com/NeonEmisionWS/NeonEmisionWS?wsdl"

2)在emitir节点上,我需要将其设置为<neon:emitir></neon:emitir>而不是常规的<emitir>

当我这样做时,一切都像魅力一样工作,就像我说的那样,我使用wsdl.exe工具创建了该类,这就是我正在使用的代码:

 [System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace = "http://neon.stoconsulting.com/NeonEmisionWS/NeonEmisionWS?wsdl", ResponseNamespace = "http://neon.stoconsulting.com/NeonEmisionWS/NeonEmisionWS?wsdl", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        [return: System.Xml.Serialization.XmlElementAttribute("RespuestaWS", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        [WebServiceSOAPExtension]
        public respuestaWS emitirWS(comprobante comprobante)
        {
            object[] results = this.Invoke("emitirWS", new object[] {
                    comprobante});
            return ((respuestaWS)(results[0]));
        }

谢谢,我不知道从哪里开始。

好吧,对于所有想做这样的事情的家伙,你都不知道,我最终做了一些我不推荐的讨厌的事情,但是如果你像我一样被困住,就不知道从哪里开始要以“正确”的方式做到这一点,那么您可以这样做:

首先,您需要创建一个扩展SoapExtension的类,如下所示:

namespace SoapExentender
{
    class WebServiceSOAPExtension : SoapExtension
    {
        Stream oldStream;
        Stream newStream;
        string filename;

    public override Stream ChainStream(Stream stream)
    {
        oldStream = stream;
        newStream = new MemoryStream();
        return newStream;
    }

    // When the SOAP extension is accessed for the first time, the XML Web service method it is applied to is accessed to store the file name passed in,

    //using the corresponding SoapExtensionAttribute.    
    public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
    {
        return null;
    }

    // The SOAP extension was configured to run using a configuration file instead of an attribute applied to a specific XML Web service method.
    public override object GetInitializer(Type WebServiceType)
    {
        return null;
    }

    // Receive the file name stored by GetInitializer and store it in a member variable for this specific instance.
    public override void Initialize(object initializer)
    {
        filename = ConfigurationManager.AppSettings["STOFacturacionDLL"].ToString();
    }

    //  If the SoapMessageStage is such that the SoapRequest or SoapResponse is still in the SOAP format to be sent or received, save it out to a file.
    public override void ProcessMessage(SoapMessage message)
    {
        switch (message.Stage)
        {
            case SoapMessageStage.BeforeSerialize:
                break;
            case SoapMessageStage.AfterSerialize: //el xml serializado de salida
                WriteOutput((SoapClientMessage)message);
                break;
            case SoapMessageStage.BeforeDeserialize:
                WriteInput((SoapClientMessage)message);
                break;
            case SoapMessageStage.AfterDeserialize:
                break;
            default:
                throw new Exception("Stage inválido");
        }
    }

    // Write the contents of the outgoing SOAP message to the log file.
    public void WriteOutput(SoapClientMessage message)
    {
        newStream.Position = 0;
        FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
        StreamWriter myStreamWriter = new StreamWriter(fs);
        myStreamWriter.WriteLine("================================== Fecha del request: " + DateTime.Now);
        // Print to the log file the request header field for SoapAction header.
        myStreamWriter.WriteLine(@"La acción SOAP del 'header' Http request  es: " + message.Action);

        // Print to the log file the method invoked by the client.
        myStreamWriter.WriteLine("El metodo llamado fue: " + message.MethodInfo.Name);

        // Print to the log file if the method invoked is OneWay.
        if (message.OneWay)
            myStreamWriter.WriteLine("El cliente no espera a que se termine el proceso (no es de un solo sentido)");
        else
            myStreamWriter.WriteLine("El cliente espera a que se termine el proceso");

        // Print to the log file the URL of the site that provides implementation of the method.
        myStreamWriter.WriteLine("La URL solicitada fue: " + message.Url);
        myStreamWriter.WriteLine("el contenido del request/response del ---- <soap:envelope> ---- es : ");
        myStreamWriter.Flush();

        Copy(newStream, fs);
        myStreamWriter.Close();
        //replace custom text
        string stringRequest = "";
        try
        {
            newStream.Position = 0;
            MemoryStream RequestStream = new MemoryStream();
            Copy(newStream, RequestStream);
            RequestStream.Position = 0;
            byte[] bytesRequestStream = ReadFully(RequestStream);
            stringRequest = System.Text.Encoding.UTF8.GetString(bytesRequestStream);
            stringRequest = replaceText(stringRequest, "<ReimprimirReferencia", "<thepanch:ReimprimirReferencia");
            int i = 0;
        }
        catch (Exception exc) { }

        newStream.Position = 0;
        //replace the original stream, with the custom stream
        Copy(ConvertStringToStream(stringRequest), oldStream);
    }

    private string replaceText(string MainString, string SearchString, string ReplaceWith)
    {
        MainString = MainString.Replace(SearchString, ReplaceWith);
        return MainString;
    }

    private MemoryStream ConvertStringToStream(string RequestString)
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(RequestString);
        MemoryStream stream = new MemoryStream(byteArray);
        stream.Position = 0;
        return stream;
    }

    private byte[] ReadFully(Stream input)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            input.CopyTo(ms);
            return ms.ToArray();
        }
    }

    public void WriteInput(SoapMessage message)
    {
        Copy(oldStream, newStream);
        FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);
        string soapString = (message is SoapServerMessage) ? "SoapRequest" : "SoapResponse";
        w.WriteLine("----------" + soapString + " at " + DateTime.Now);
        w.Flush();
        newStream.Position = 0;
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
    }

    void Copy(Stream from, Stream to)
    {
        TextReader reader = new StreamReader(from);
        TextWriter writer = new StreamWriter(to);
        writer.WriteLine(reader.ReadToEnd());
        writer.Flush();
    }
}

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class WebServiceSOAPExtensionAttribute : SoapExtensionAttribute
{
    private int priority;

    public override Type ExtensionType
    {
        get { return typeof(WebServiceSOAPExtension); }
    }

    public override int Priority
    {
        get { return priority; }
        set { priority = value; }
    }
}

}

然后在代理的方法上使用自定义属性,用您的自定义流替换实际的Stream,writeOutput方法用于“ request”,writeInput方法用于“ response”,那么您需要使用字符串来适应您的需求,希望对您有所帮助。

正如我在第一行中提到的那样,这不是正确的方法,但是,如果您像我一样不知道从哪里开始,则可以编写自定义Xml字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM