Классы SOAP XML для C # - PullRequest
       21

Классы SOAP XML для C #

0 голосов
/ 23 декабря 2018

Привет, ребята, я новичок в мыле, и мы начали работать с каким-то сервисом, который делает почтовые звонки в мой asmx с помощью xml.внутри моего проекта в файле asmx мне нужно построить модель, которую я получаю от них.поэтому у меня есть xml:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Exit xmlns="http://tempuri.org/">
<UserName>daniel@xxx.com</UserName>
<Password>123456</Password>
<parkingLotId>21</parkingLotId>
<gateNumber>EX 41</gateNumber>
<ticketNumber>123123123123123123123</ticketNumber>
<plateNumber>12211221</plateNumber>
<paymentSum>10.0</paymentSum>
<ExitDateTime>2018-12-23T09:56:10</ExitDateTime>
<referenceId>987462187346238746263</referenceId>
</Exit>
</s:Body>
</s:Envelope>

, когда я вставляю этот xml в визуальную студию. Edit -> Special Pase -> Paste XML As Class, он создает модель для меня с атрибутами xml, такими как:

[XmlRoot(ElementName = "Exit", Namespace = "http://tempuri.org/")]
public class Exit
{
    [XmlElement(ElementName = "UserName", Namespace = "http://tempuri.org/")]
    public string UserName { get; set; }
     ....
}

[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
    [XmlElement(ElementName = "Exit", Namespace = "http://tempuri.org/")]
    public Exit Exit { get; set; }
}

[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
    [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public Body Body { get; set; }
    [XmlAttribute(AttributeName = "s", Namespace = "http://www.w3.org/2000/xmlns/")]
    public string S { get; set; }
}

но!я получаю сообщение об ошибке каждый раз, когда я делаю POST-запрос с этими данными:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <soap:Fault>
            <soap:Code>
                <soap:Value>soap:Receiver</soap:Value>
            </soap:Code>
            <soap:Reason>
                <soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.Xml.XmlException: Root element is missing.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
   at System.Xml.XmlReader.MoveToContent()
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
   at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
   at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
   at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
   at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean&amp; abortProcessing)
   --- End of inner exception stack trace ---</soap:Text>
            </soap:Reason>
            <soap:Detail />
        </soap:Fault>
    </soap:Body>
</soap:Envelope>

, и это мой код:

[WebMethod]
        public string Exit()
        {
            XmlDocument xmlSoapRequest = new XmlDocument();
            using (Stream receiveStream = HttpContext.Current.Request.InputStream)
            {
                receiveStream.Position = 0;
                using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { xmlSoapRequest.Load(readStream); }
            }
            var password = xmlSoapRequest?.GetElementsByTagName("Password")?.Item(0)?.FirstChild?.Value;
            var userName = xmlSoapRequest?.GetElementsByTagName("UserName")?.Item(0)?.FirstChild?.Value;
            var parkingLotId = xmlSoapRequest?.GetElementsByTagName("parking_lot_Id")?.Item(0)?.FirstChild?.Value;
            var gateNumber = xmlSoapRequest?.GetElementsByTagName("gateNumber")?.Item(0)?.FirstChild?.Value;
            var plateNumber = xmlSoapRequest?.GetElementsByTagName("plateNumber")?.Item(0)?.FirstChild?.Value;
            var paymentSum = xmlSoapRequest?.GetElementsByTagName("paymentSum")?.Item(0)?.FirstChild?.Value;
            var exitDateTime = xmlSoapRequest?.GetElementsByTagName("ExitDateTime")?.Item(0)?.FirstChild?.Value;
            var referenceId = xmlSoapRequest?.GetElementsByTagName("referenceId")?.Item(0)?.FirstChild?.Value;

            var exitParking = new Exit
            {
                ExitDateTime = Convert.ToDateTime(exitDateTime),
                gateNumber = gateNumber,
                parkingLotId = Convert.ToByte(parkingLotId),
                Password = Convert.ToUInt32(password),
                paymentSum = Convert.ToDecimal(paymentSum),
                plateNumber = Convert.ToUInt32(plateNumber),
                referenceId = referenceId,
                UserName = userName
            };

            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            var jsonObject = jsonSerializer.Serialize(exitParking);
            var content = new StringContent(jsonObject, Encoding.UTF8, "application/json");
            HttpClient client = new HttpClient();
            var result = client.PostAsync("http://merchant-api-eb-parking-prod.eu-west-1.elasticbeanstalk.com/v1/parkings/exit", content).Result;

            Context.Response.Output.Write($"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Body><ExitResponse xmlns=\"http://tempuri.org/\"><ExitResult xmlns:a=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:i=\"http://www.w3.org/2001/XMLSchema\"><a:Status>OK</a:Status></ExitResult></ExitResponse></s:Body></s:Envelope>");

            Context.Response.ContentType = "text/xml";
            Context.Response.End();
            return string.Empty;
        }

я могу видеть данные, которые я публикую в Global.asax в ЗапросеОбъект я вижу xml, который я публикую как строку, но после глобального asax он выдает исключение.

У меня есть атрибут Root, но в исключении он говорит: Root элемент отсутствует

Спасибо!

1 Ответ

0 голосов
/ 30 декабря 2018

Хорошо, разобрался!причина ошибки:

<Exit xmlns="http:--tempuri-org-">

пространство имен (xmlns) должно быть URL моего сайта на сервере

http:--mysite-com-

вместо

http:--tempuri-org-
...