简体   繁体   English

XML 文档 (1,2) 中存在错误,System.InvalidOperationException:<authorizationresult xlms:""> 没想到</authorizationresult>

[英]There is an error in XML document (1,2) , System.InvalidOperationException: <AuthorizationResult xlms:""> was not expected

XML sent from API从 API 发送的 XML

<AuthenticationResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<PAPIErrorCode>0</PAPIErrorCode>
<ErrorMessage/>
<AccessToken>StringAccessToken</AccessToken>
<AccessSecret>StringAccessToken</AccessSecret>
<PolarisUserID>PolarisSampleUser</PolarisUserID>
<BranchID>7</BranchID>
<AuthExpDate>2013-05-27T16:57:46.323</AuthExpDate>
</AuthenticationResult>

Classes for Response响应类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace PAPIAutomatedTestingTool
{
    [XmlRoot(ElementName="AuthorizationResult")]
    public class AuthorizationResult
    {
        public int PAPIErrorCode { get; set; }

        public string ErrorMessage { get; set; }

        public string AccessToken { get; set; }

        public string AccessSecret { get; set; }

        public int PolarisUserID { get; set; }

        public int BranchID { get; set; }

        public DateTime AuthExpDate { get; set; }
    }
}

Code making request and deserializing代码制作请求和反序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Security.Cryptography;
using System.Xml;
using System.Xml.Serialization;

namespace PAPIAutomatedTestingTool
{
    public class APICallMethods
    {
        public string URI { get; set; }
        public string accSecret { get; set; }
        public string accToken { get; set; }
        public string authorizationString { get; set; }

        public bool AuthenticateStaffUser()
        {
            try
            {

            //Initializing all variables
            string authReqMethod = "POST";
            string authAccessKey = "Sample Access Key";
            string authAccessKeyID = "Sample Access ID";
            string authPatronPassword = "";
            DateTime authDateTime = DateTime.Now;
            string httpAuthDateTime = authDateTime.ToUniversalTime().ToString("r");
            string authURI = "Sample URI";


            //Composing the papiHash from the given parameters
            string papiHash = GetPAPIHash(authAccessKey, authReqMethod, authURI, httpAuthDateTime, authPatronPassword);
            //Formating the authorization string 
            string authorizationString = String.Format("Authorization: PWS {0}:{1}", authAccessKeyID, papiHash);


            //Creating and defining the WebRequest
            WebRequest req = WebRequest.Create(authURI);
            req.Method = "POST";
            req.Headers.Add("PolarisDate", httpAuthDateTime);
            req.Headers.Add(authorizationString);
            req.ContentType = "application/xml";
            string requestBody = "<AuthenticationData><Domain>SampleDomain</Domain><Username>SampleUsername</Username><Password>SamplePassword</Password></AuthenticationData>";
            byte[] reqBodyBytes = System.Text.Encoding.UTF8.GetBytes(requestBody);
            req.ContentLength = reqBodyBytes.Length;
            using (Stream requestStream = req.GetRequestStream())
            {
                requestStream.Write(reqBodyBytes, 0, reqBodyBytes.Length);
            }


            //Receiving the WebResponse
            using (WebResponse resp = req.GetResponse())
            {
                AuthorizationResult firstResponse = new AuthorizationResult();
                Stream respStream = resp.GetResponseStream();
                StreamReader sr = new StreamReader(respStream);


                XmlSerializer xmlSerializer = new XmlSerializer(typeof(AuthorizationResult));
                firstResponse = (AuthorizationResult)xmlSerializer.Deserialize(respStream);
                Console.WriteLine("Authorization: PWS" + firstResponse.AccessSecret + ":" + firstResponse.AccessToken);
                return true;
            }
        }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }

        }


        public string GetPAPIHash(string strAccessKey, string strHTTPMethod, string strURI, string strHTTPDate, string strPatronPassword)
        {
            byte[] secretBytes = UTF8Encoding.UTF8.GetBytes(strAccessKey);
            HMACSHA1 hmac = new HMACSHA1(secretBytes);

            byte[] dataBytes = null;

            if (strPatronPassword.Length > 0)
            {
                dataBytes = UTF8Encoding.UTF8.GetBytes(strHTTPMethod + strURI + strHTTPDate + strPatronPassword);
            }
            else
            {
                dataBytes = UTF8Encoding.UTF8.GetBytes(strHTTPMethod + strURI + strHTTPDate);
            }
            byte[] computedHash = hmac.ComputeHash(dataBytes);
            string computedHashString = Convert.ToBase64String(computedHash);

            return computedHashString;
        }
    }
}

I am making a POST request to the API with a body that contains AuthorizationData.我正在使用包含 AuthorizationData 的正文向 API 发出 POST 请求。 The API is supposed to return the xml to deserialize into firstresponse. API 应该返回 xml 以反序列化为第一响应。 I have received the xml(confirmed by printing to console) but i am receiving the There is an error in the XML Document(1,2) and <AuthorizationData xmlns=""> was not expected.我收到了 xml(通过打印到控制台确认),但我收到了There is an error in the XML Document(1,2) and <AuthorizationData xmlns=""> was not expected. Thanks for the help in advance.我在这里先向您的帮助表示感谢。

It appears to be complaining about an unexpected root element and there is some confusion surrounding that elsewhere in your question. 它似乎在抱怨意外的根元素,并且在你的问题的其他地方存在一些混乱。

In the question title you have <AuthorizationResult> 在问题标题中,您有<AuthorizationResult>

In the example XML response you have <AuthenticationResult> 在示例XML响应中,您有<AuthenticationResult>

In the C# you have [XmlRoot(ElementName="AuthorizationResult")] 在C#中你有[XmlRoot(ElementName="AuthorizationResult")]

At the end of your question you mention <AuthorizationData> 在您的问题的最后,您提到<AuthorizationData>

That's quite a few subtle variations on a theme. 这是一个主题的相当微妙的变化。

Assuming the XML sample response is correct, you should change the C# to expect the root element to be <AuthenticationResult> ... 假设XML样本响应是正确的,您应该更改C#以期望根元素为<AuthenticationResult> ...

[XmlRoot(ElementName="AuthenticationResult")]
public class AuthenticationResult
{
    ...

If you want to write a single deserialize for both schema and non-schema custom XMLs, you can turn off namespaces to avoid getting the 'There is an error in the XML Document(1,2)' error.如果您想为模式和非模式自定义 XML 编写单个反序列化,您可以关闭命名空间以避免出现“XML 文档 (1,2) 中存在错误”错误。 But since the XmlReader expects an XML Schema, you can read it with StringReader class then use XmlReader object to remove custom namespaces.但由于 XmlReader 需要一个 XML 架构,您可以使用 StringReader 类读取它,然后使用 XmlReader 对象删除自定义命名空间。

//Namespaces
using System.IO;
using System.Xml.Serialization;

//Field
private static XmlSurrogates.Root _xmlSurrogates = new();

//Method
   private static void DeserializeXml(string xml)
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(_xmlSurrogates.GetType());
                using (StringReader reader = new StringReader(xml))
                {
                    var xmlTextReader = new System.Xml.XmlTextReader(reader);
                    xmlTextReader.Namespaces = false;
                    _xmlSurrogates = (XmlSurrogates.Root)(serializer.Deserialize(xmlTextReader));
                }
            }
            catch (Exception ex)
            {
                Log.Error($"There is an error while deserialize. Error: {ex.Message}");
            }
        }

//Root Model Example
public class XmlSurrogates
    {
        [XmlRoot(ElementName = "XMLROOTELEMENTNAMEHERE FOR THIS ITS root")]
        public class Root
        {
            [XmlElement(ElementName = "Boo")] public Boo Boo { get; set; }
            [XmlElement(ElementName = "Control")] public ClassName DeclareName { get; set; }
            [XmlAttribute(AttributeName = "MainCode")] public string MainCode { get; set; }
            [XmlAttribute(AttributeName = "Caption")] public string Caption { get; set; }
        }

        [XmlRoot(ElementName = "Boo")]
        public class ElementAsClassName
        {
            [XmlAttribute(AttributeName = "Foo")] public string PropertyName { get; set; }
        }
    }

暂无
暂无

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

相关问题 System.InvalidOperationException:&#39;XML文档(0,0)中存在错误。 - System.InvalidOperationException: 'There is an error in XML document (0, 0).' System.InvalidOperationException: 'XML 文档 (1, 1) 中存在错误。 - System.InvalidOperationException: 'There is an error in the XML document (1, 1).' XML序列化:System.InvalidOperationException: <tagname> 没想到 - XML Serialization: System.InvalidOperationException: <tagname> was not expected XML文档的序列化(System.InvalidOperationException) - Serialization of XML Document (System.InvalidOperationException) C#XML错误:System.InvalidOperationException - C# XML Error: System.InvalidOperationException XML 反序列化 System.InvalidOperationException”<objects xmlns=""> 没想到</objects> - XML deserialization System.InvalidOperationException” the <Objects xmlns=''> was not expected WSDL.exe生成的客户端提供:未处理的异常:System.InvalidOperationException:XML文档中有错误(…) - WSDL.exe generated client gives: Unhandled Exception: System.InvalidOperationException: There is an error in XML document (…) DropDownList 错误,System.InvalidOperationException - DropDownList Error, System.InvalidOperationException C#XML:System.InvalidOperationException - C# XML: System.InvalidOperationException Xml序列化-System.InvalidOperationException:是否无法序列化“ this”? - Xml Serialization - System.InvalidOperationException: Is it not possible to serialize 'this'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM