gpt4 book ai didi

c# - RestSharp 方法抛出 System.Xml.XMlException "="是意外标记。预期的 token 是 ';'

转载 作者:太空狗 更新时间:2023-10-29 19:38:17 27 4
gpt4 key购买 nike

我查看了 this question 的答案并查看无效字符可能导致引发此错误的问题。我的问题有点不同,因为我使用 RestSharp 进行如下 API 调用:

 private static T Execute<T>(IRestRequest request, string baseUrl) where T : class, new()
{
var client = new RestClient(baseUrl);
var response = client.Execute<T>(request);

if (response.ErrorException != null)
{
Console.WriteLine(
"Error: Exception: {0}, Headers: {1}, Content: {2}, Status Code: {3}",
response.ErrorException,
response.Headers,
response.Content,
response.StatusCode);
}

return response.Data;
}

public static ProPayResponse MerchantSignUpForProPay()
{
var baseUrl = "https://xmltestapi.propay.com/ProPayAPI";
var request = BuildMerchantTestData();
var restRequest = CreateRestRequest("SignUp", Method.PUT);
restRequest.AddJsonBody(request);
return Execute<ProPayResponse>(restRequest, baseUrl);
}

private static async Task<RestRequest> CreateRestRequest(string resource, Method method)
{

var credentials = GetCredentials();

var restRequest = new RestRequest { Resource = resource, Method = method, RequestFormat = DataFormat.Json, };
restRequest.AddHeader("accept", "application/json");
restRequest.AddHeader("Authorization", credentials);
return restRequest;
}
private static string GetCredentials()
{
var termId = "myterm"; // put affiliate term id here, if you have it
var certString = "mycertString"; // put affiliate cert string here
var encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(certString + ":" + termId));

var credentials = $"Basic {encodedCredentials}";
return credentials;
}

异常的完整堆栈跟踪如下:

Error: Exception: System.Xml.XmlException: '=' is an unexpected token. The expected token is ';'. Line 26, position 43.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken(String expectedToken1, String expectedToken2)
at System.Xml.XmlTextReaderImpl.HandleEntityReference(Boolean isInAttributeValue, EntityExpandType expandType, Int32& charRefEndPos)
at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars)
at System.Xml.XmlTextReaderImpl.FinishPartialValue()
at System.Xml.XmlTextReaderImpl.get_Value()
at System.Xml.Linq.XContainer.ContentReader.ReadContentFrom(XContainer rootContainer, XmlReader r)
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text, LoadOptions options)
at RestSharp.Deserializers.XmlDeserializer.Deserialize[T](IRestResponse response)
at RestSharp.RestClient.Deserialize[T](IRestRequest request, IRestResponse raw), Headers: System.Collections.Generic.List`1[RestSharp.Parameter], Content:

当我运行这段代码时,我确实注意到在堆栈跟踪的内容部分抛出一个 HTTP 404。

我认为这意味着我有一个不正确的 baseURl 但我不确定并且想知道是否是这种情况或者我的代码是否还有其他问题?

更新:进一步研究这个问题后,我认为引发错误是因为我在发送 RestRequest 之前没有将我的模型对象序列化为 JSON。

我是否需要在发出请求之前序列化所有对象?

更新 2:多亏了第二双眼睛,我更正了 URL。现在,当我运行我的应用程序时,会抛出以下错误:

Error: Exception: System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Parse(String text, LoadOptions options)
at RestSharp.Deserializers.XmlDeserializer.Deserialize[T](IRestResponse response)
at RestSharp.RestClient.Deserialize[T](IRestRequest request, IRestResponse raw), Message: Data at the root level is invalid. Line 1, position 1., Headers: System.Collections.Generic.List`1[RestSharp.Parameter], Content: ?<?xml version="1.0" encoding="utf-8"?>

最佳答案

I think the error is being thrown because I'm not serializing my model objects into JSON before sending the RestRequest.

restRequest.AddJsonBody(request); 将序列化对象并将适当的 header 添加到请求中。堆栈跟踪看起来问题出在以 XML 形式返回的响应以及尝试对其进行反序列化时发生的情况。

When I run this code, I do note that an HTTP 404 is thrown in the content section of the stack trace.

I think this means that I have an incorrect baseURl but am not sure and would like to know if this is the case or if my code has other issues?

快速浏览一下他们的文档,您似乎在调用他们的 (SOAP) XML API。因此,如果您打算与 ProPay REST 接口(interface)交互,那么您调用了错误的基本 URL。

对于 REST,它们显示以下内容

Resource URI and HTTP Methods

The request URI is constructed from a Base URI and a Resource URI appended. A Resource URI may be used differently based on the HTTP verb of the request. Consider the following Example:

ProPay Integration environment Base URI: https://xmltestapi.propay.com
Resource: /propayAPI/signup
HTTP Method: PUT
Request Endpoint: PUT https://xmltestapi.propay.com/propayapi/signup

这意味着您需要更新代码

public static async Task<ProPayResponse> MerchantSignUpForProPay() {
var baseUrl = "https://xmltestapi.propay.com/propayapi";
var content = await BuildMerchantTestData();
var request = CreateRestRequest("Signup", Method.PUT);
request.AddJsonBody(content);
return await Execute<ProPayResponse>(request, baseUrl);
}

private static async Task<T> Execute<T>(IRestRequest request, string baseUrl)
where T : class, new() {
var client = new RestClient(baseUrl);
var response = await client.ExecuteTaskAsync<T>(request);

if (response.ErrorException != null) {
Console.WriteLine(
"Error: Exception: {0}, Headers: {1}, Content: {2}, Status Code: {3}",
response.ErrorException,
response.Headers,
response.Content,
response.StatusCode);
}

return response.Data;
}

private static RestRequest CreateRestRequest(string resource, Method method) {
var credentials = GetCredentials();
var restRequest = new RestRequest(resource, method, DataFormat.Json);
restRequest.AddHeader("Accept", "application/json");
restRequest.AddHeader("Authorization", credentials);
return restRequest;
}

我建议使基本 URL 可配置而不是硬编码,这样它就可以在投入生产时轻松更改而无需重新编译。

关于c# - RestSharp 方法抛出 System.Xml.XMlException "="是意外标记。预期的 token 是 ';',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410745/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com